samagotchi 0.164.0 → 0.166.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 (100) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +88 -1
  3. data/docs/architecture.md +7 -5
  4. data/docs/cli.md +23 -12
  5. data/docs/configuration.md +8 -2
  6. data/docs/guardrails.md +19 -18
  7. data/docs/internals/block-renderers.md +1 -1
  8. data/docs/internals/bridge.md +10 -3
  9. data/docs/internals/bundles.md +4 -2
  10. data/docs/internals/inline-widgets.md +8 -1
  11. data/docs/internals/remote-sessions.md +1 -1
  12. data/docs/internals/web-frontend.md +73 -13
  13. data/docs/memory.md +12 -7
  14. data/docs/plugins.md +6 -4
  15. data/docs/releasing.md +17 -4
  16. data/docs/scheduling.md +25 -3
  17. data/docs/sessions.md +12 -10
  18. data/docs/testing.md +37 -4
  19. data/lib/samagotchi/block_renderers.rb +3 -6
  20. data/lib/samagotchi/bridge/card_store.rb +2 -1
  21. data/lib/samagotchi/bridge/turn_accumulator.rb +7 -8
  22. data/lib/samagotchi/bridge.rb +45 -3
  23. data/lib/samagotchi/bundle_command/installed_check.rb +2 -1
  24. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  25. data/lib/samagotchi/chi_home.rb +44 -2
  26. data/lib/samagotchi/client_id.rb +34 -3
  27. data/lib/samagotchi/compat.rb +34 -0
  28. data/lib/samagotchi/context_command.rb +3 -0
  29. data/lib/samagotchi/context_providers.rb +5 -6
  30. data/lib/samagotchi/context_sources.rb +2 -2
  31. data/lib/samagotchi/continue_intent.rb +50 -5
  32. data/lib/samagotchi/events.rb +4 -4
  33. data/lib/samagotchi/extension_load.rb +2 -1
  34. data/lib/samagotchi/guardrails/approvals.rb +36 -9
  35. data/lib/samagotchi/guardrails/child_boundary.rb +7 -27
  36. data/lib/samagotchi/guardrails/rules.rb +11 -9
  37. data/lib/samagotchi/guardrails/targets.rb +3 -4
  38. data/lib/samagotchi/inline_widgets.rb +16 -1
  39. data/lib/samagotchi/memory_bundle/provenance.rb +46 -4
  40. data/lib/samagotchi/memory_bundle/status.rb +2 -1
  41. data/lib/samagotchi/memory_command.rb +3 -0
  42. data/lib/samagotchi/memory_orphans.rb +4 -7
  43. data/lib/samagotchi/memory_paths.rb +64 -7
  44. data/lib/samagotchi/memory_usage.rb +1 -1
  45. data/lib/samagotchi/plugin/sessions.rb +8 -3
  46. data/lib/samagotchi/project_command.rb +4 -1
  47. data/lib/samagotchi/project_id_clash.rb +37 -26
  48. data/lib/samagotchi/project_init.rb +24 -7
  49. data/lib/samagotchi/reply_wait/poll.rb +4 -14
  50. data/lib/samagotchi/reply_wait.rb +0 -23
  51. data/lib/samagotchi/run_options.rb +1 -1
  52. data/lib/samagotchi/schedules.rb +124 -106
  53. data/lib/samagotchi/send_command.rb +71 -18
  54. data/lib/samagotchi/session.rb +3 -2
  55. data/lib/samagotchi/session_access/local.rb +19 -2
  56. data/lib/samagotchi/session_access/remote.rb +13 -17
  57. data/lib/samagotchi/session_chain/links.rb +109 -0
  58. data/lib/samagotchi/session_chain.rb +7 -19
  59. data/lib/samagotchi/session_continue.rb +138 -54
  60. data/lib/samagotchi/session_inbox.rb +1 -1
  61. data/lib/samagotchi/session_inbox_delivery.rb +57 -38
  62. data/lib/samagotchi/session_manager/delivery.rb +104 -18
  63. data/lib/samagotchi/session_manager/removal.rb +13 -7
  64. data/lib/samagotchi/session_manager.rb +1 -0
  65. data/lib/samagotchi/session_retention.rb +20 -10
  66. data/lib/samagotchi/session_setup.rb +31 -1
  67. data/lib/samagotchi/state_format.rb +12 -8
  68. data/lib/samagotchi/terminal_ui/attach_launcher.rb +6 -7
  69. data/lib/samagotchi/terminal_ui.rb +20 -9
  70. data/lib/samagotchi/tools/delegate.rb +2 -3
  71. data/lib/samagotchi/verify_fresh.rb +4 -1
  72. data/lib/samagotchi/version.rb +1 -1
  73. data/lib/samagotchi/web/public/activity.js +2 -2
  74. data/lib/samagotchi/web/public/app.js +28 -21
  75. data/lib/samagotchi/web/public/auth_lost.js +3 -1
  76. data/lib/samagotchi/web/public/bar_fold.js +293 -0
  77. data/lib/samagotchi/web/public/card.js +1 -1
  78. data/lib/samagotchi/web/public/chip_popover.js +5 -1
  79. data/lib/samagotchi/web/public/composer_mode.js +5 -7
  80. data/lib/samagotchi/web/public/delivery_line.js +19 -4
  81. data/lib/samagotchi/web/public/index.html +242 -94
  82. data/lib/samagotchi/web/public/info_bar.js +28 -16
  83. data/lib/samagotchi/web/public/info_bar_model.js +76 -2
  84. data/lib/samagotchi/web/public/live_timing.js +3 -0
  85. data/lib/samagotchi/web/public/more_sheet.js +98 -40
  86. data/lib/samagotchi/web/public/resync_reach.js +59 -0
  87. data/lib/samagotchi/web/public/session_fields.js +1 -0
  88. data/lib/samagotchi/web/public/session_state.js +5 -0
  89. data/lib/samagotchi/web/public/stage_frame.js +4 -2
  90. data/lib/samagotchi/web/public/stage_stall.js +134 -0
  91. data/lib/samagotchi/web/public/stage_view.js +78 -7
  92. data/lib/samagotchi/web/public/stream_handlers.js +1 -1
  93. data/lib/samagotchi/web/public/turn_events.js +0 -122
  94. data/lib/samagotchi/web/public/turn_model.js +1 -1
  95. data/lib/samagotchi/web/public/widget_picks.js +18 -3
  96. data/lib/samagotchi/web/session_control.rb +15 -2
  97. data/lib/samagotchi/web/session_create.rb +4 -2
  98. data/lib/samagotchi/web/token.rb +2 -2
  99. data/lib/samagotchi/web/update_check.rb +27 -8
  100. metadata +5 -1
@@ -12,6 +12,7 @@ require_relative "worker_presence"
12
12
  require_relative "client_id"
13
13
  require_relative "command_intake"
14
14
  require_relative "config"
15
+ require_relative "continue_intent"
15
16
  require_relative "continue_offer"
16
17
  require_relative "delivery"
17
18
  require_relative "log"
@@ -199,13 +200,13 @@ module Samagotchi
199
200
  end
200
201
 
201
202
  def protected_session_ids
202
- index = Index.new(@state_dir)
203
- entries.flat_map { |entry| [entry.anchor, entry.head, target_of(entry, index).first] }.compact.uniq
203
+ links = links_now
204
+ entries.flat_map { |entry| [entry.anchor, entry.head, target_of(entry, links).first] }.compact.uniq
204
205
  end
205
206
 
206
207
  def protecting(session_id)
207
- index = Index.new(@state_dir)
208
- entries.find { |entry| target_of(entry, index).first == session_id }
208
+ links = links_now
209
+ entries.find { |entry| target_of(entry, links).first == session_id }
209
210
  end
210
211
 
211
212
  # @param id_or_name [String] an id, a unique prefix of one, or a title
@@ -303,11 +304,11 @@ module Samagotchi
303
304
  # its anchor or its head is one of them.
304
305
  # @return [Array<String>]
305
306
  def chain_of(session_id)
306
- index = Index.new(@state_dir)
307
- head = index.latest(session_id)
307
+ links = links_now
308
+ head = links.latest(session_id)
308
309
  ids = [head]
309
310
  id = head
310
- while (previous = index.continues(id)) && !ids.include?(previous)
311
+ while (previous = links.continues(id)) && !ids.include?(previous)
311
312
  ids << previous
312
313
  id = previous
313
314
  end
@@ -348,7 +349,7 @@ module Samagotchi
348
349
  outcomes = []
349
350
  pending = []
350
351
  prune_after = []
351
- index = nil
352
+ links = nil
352
353
 
353
354
  FileUtils.mkdir_p(@store_dir)
354
355
  FileUtils.mkdir_p(@state_dir)
@@ -407,18 +408,19 @@ module Samagotchi
407
408
  next
408
409
  end
409
410
 
410
- # One session listing for the whole tick: a chain walk re-globbing
411
- # every session per call is the tick's dominant cost.
412
- index = Index.new(@state_dir)
411
+ # One session listing for the whole tick (one SessionChain::Links): a
412
+ # chain walk re-globbing every session per call is the tick's
413
+ # dominant cost.
414
+ links = links_now
413
415
  # One firing per chain per tick. A second chain entry of the same chain
414
416
  # would continue the link the first one just made: that link has no
415
- # worker lock yet and is not in this tick's index, so the busy check
417
+ # worker lock yet and is not in this tick's listing, so the busy check
416
418
  # cannot see it, and its prompt would be archived before it ever ran.
417
- fired_chains = resolved_chains.to_h { |entry| [chain_key(index, entry), true] }
418
- pending_chains = in_flight.select { |entry| entry.mode == CHAIN }.map { |entry| chain_key(index, entry) }
419
+ fired_chains = resolved_chains.to_h { |entry| [chain_key(links, entry), true] }
420
+ pending_chains = in_flight.select { |entry| entry.mode == CHAIN }.map { |entry| chain_key(links, entry) }
419
421
  due.each do |entry|
420
422
  position = updated.index { |candidate| candidate.is_a?(Entry) && candidate.id == entry.id }
421
- verdict = check(entry, index)
423
+ verdict = check(entry, links)
422
424
  if verdict
423
425
  kind, reason = verdict
424
426
  unless dry_run
@@ -428,20 +430,20 @@ module Samagotchi
428
430
  detail: reason, entry: entry)
429
431
  next
430
432
  end
431
- if entry.mode == CHAIN && fired_chains[chain_key(index, entry)]
433
+ if entry.mode == CHAIN && fired_chains[chain_key(links, entry)]
432
434
  reason = "the chain just fired; retry at the next tick"
433
435
  updated[position] = skipped(entry, reason) unless dry_run
434
436
  outcomes << Outcome.new(id: entry.id, title: entry.title, status: "skipped", detail: reason, entry: entry)
435
437
  next
436
438
  end
437
- if entry.mode == CHAIN && pending_chains.include?(chain_key(index, entry))
439
+ if entry.mode == CHAIN && pending_chains.include?(chain_key(links, entry))
438
440
  reason = "a schedule turn is still pending in this chain"
439
441
  updated[position] = skipped(entry, reason) unless dry_run
440
442
  outcomes << Outcome.new(id: entry.id, title: entry.title, status: "skipped", detail: reason, entry: entry)
441
443
  next
442
444
  end
443
445
  if dry_run
444
- fired_chains[chain_key(index, entry)] = true if entry.mode == CHAIN
446
+ fired_chains[chain_key(links, entry)] = true if entry.mode == CHAIN
445
447
  outcomes << Outcome.new(id: entry.id, title: entry.title, status: "dry", detail: entry.recurrence_words, entry: entry)
446
448
  next
447
449
  end
@@ -453,18 +455,18 @@ module Samagotchi
453
455
  advanced = advance(entry, now)
454
456
  updated[position] = advanced
455
457
  pending << advanced
456
- fired_chains[chain_key(index, entry)] = true if entry.mode == CHAIN
458
+ fired_chains[chain_key(links, entry)] = true if entry.mode == CHAIN
457
459
  end
458
460
  write(file: file.with(entries: updated, attributes: file.attributes.merge(last_tick_at: now.utc.iso8601))) unless dry_run
459
461
  end
460
462
 
461
463
  pending.each do |entry|
462
- outcome = fire_and_record(entry, index)
464
+ outcome = fire_and_record(entry, links)
463
465
  outcomes << outcome
464
466
  prune_after << outcome.entry if outcome.status == "fired" && entry.mode == CHAIN && entry.keep_links.positive?
465
467
  end
466
- index ||= Index.new(@state_dir) unless prune_after.empty?
467
- prune_after.each { |entry| prune(entry, index) }
468
+ links ||= links_now unless prune_after.empty?
469
+ prune_after.each { |entry| prune(entry, links) }
468
470
  Tick.new(locked: false, outcomes: outcomes)
469
471
  end
470
472
 
@@ -479,7 +481,7 @@ module Samagotchi
479
481
  entry = lookup(id_or_name)
480
482
  return Outcome.new(id: id_or_name.to_s, status: "failed", detail: "no such schedule") if entry.nil?
481
483
 
482
- index = Index.new(@state_dir)
484
+ links = links_now
483
485
  reserved = nil
484
486
  outcome = nil
485
487
  write_under_lock do |file|
@@ -501,7 +503,7 @@ module Samagotchi
501
503
  next
502
504
  end
503
505
 
504
- verdict = check(current, index)
506
+ verdict = check(current, links)
505
507
  if verdict
506
508
  kind, reason = verdict
507
509
  status = kind == :skip ? "skipped" : "failed"
@@ -518,7 +520,7 @@ module Samagotchi
518
520
  return outcome if outcome
519
521
  return Outcome.new(id: entry.id, title: entry.title, status: "failed", detail: "no such schedule") unless reserved
520
522
 
521
- fire_and_record(reserved, index)
523
+ fire_and_record(reserved, links)
522
524
  end
523
525
 
524
526
  # Minutes between the hub's ticks when schedule.auto_tick is on.
@@ -578,50 +580,6 @@ module Samagotchi
578
580
  end
579
581
  end
580
582
 
581
- # The chain a tick walks: the sessions once, with their predecessors,
582
- # their successors and whether they are archived.
583
- class Index
584
- def initialize(state_dir)
585
- @state_dir = state_dir
586
- sessions = Session.list(state_dir: state_dir, include_archived: true, sort: "created_at", order: "asc")
587
- @by_id = sessions.to_h { |session| [session.id, session] }
588
- @archived = @by_id.to_h { |id, _session| [id, ArchiveStore.archived?(Session.session_dir(id, state_dir: state_dir))] }
589
- @nexts = {}
590
- sessions.each { |session| @nexts[session.continues] ||= session.id if session.continues }
591
- end
592
-
593
- def session(id) = @by_id[id]
594
-
595
- def gone?(id) = @by_id[id].nil?
596
-
597
- def archived?(id) = @archived[id]
598
-
599
- attr_reader :state_dir
600
-
601
- # The chain's latest link from +id+ on, in this one listing.
602
- def latest(id)
603
- seen = [id]
604
- while (following = @nexts[seen.last]) && !seen.include?(following)
605
- seen << following
606
- end
607
- seen.last
608
- end
609
-
610
- # A link's predecessor, or nil (a pruned or never-existing one).
611
- def continues(id) = @by_id[id]&.continues
612
-
613
- # A chain's root: +id+ back through `continues` until a link with no
614
- # predecessor. Entries of one chain share this root whichever link each
615
- # of them was added against.
616
- def root(id)
617
- seen = [id]
618
- while (previous = @by_id[seen.last]&.continues) && !seen.include?(previous)
619
- seen << previous
620
- end
621
- seen.last
622
- end
623
- end
624
-
625
583
  # The length of an interval in seconds; nil for something that is not an
626
584
  # interval, and nil for zero so a `0m` schedule can never fire every tick.
627
585
  def self.interval_seconds(interval)
@@ -677,6 +635,11 @@ module Samagotchi
677
635
 
678
636
  private
679
637
 
638
+ # The chains as they are now, over one session listing (SessionChain::Links):
639
+ # one per tick, passed wherever a target is resolved, so the check, the
640
+ # one-firing-per-chain guard and the firing see the same chain.
641
+ def links_now = SessionChain::Links.new(state_dir: @state_dir)
642
+
680
643
  # @param strict [Boolean] a file that is not readable JSON raises rather
681
644
  # than reading as empty: a write starting from an empty list would rewrite
682
645
  # the file and lose every schedule on it. Listing stays lenient.
@@ -942,50 +905,77 @@ module Samagotchi
942
905
  end
943
906
  end
944
907
 
945
- # :skip (busy now, try the next tick) or :fail (the target is gone or
946
- # archived); nil when the entry may fire.
947
- def check(entry, index)
948
- target, reason = target_of(entry, index)
949
- return [:fail, reason] if target.nil?
908
+ # :skip (busy now, or being continued: try the next tick) or :fail (the
909
+ # target is gone or archived); nil when the entry may fire. The
910
+ # continue's skip comes before the busy check: its successor holds no
911
+ # worker lock yet, and the old link's busy signals say nothing.
912
+ def check(entry, links)
913
+ target, reason, kind = target_of(entry, links)
914
+ return [kind || :fail, reason] if target.nil?
950
915
 
951
- busy_reason(entry, index, target)
916
+ busy_reason(entry, links, target)
952
917
  end
953
918
 
954
919
  # The session the entry would act on: its head, followed through every
955
920
  # continue made since it was last written — a chain firing's new link or a
956
- # human `chi send --continues`/`chi resume` (SessionChain.latest, the same
957
- # walk SessionContinue.run does for `last:`). Both modes use the walk: a
921
+ # person's `chi send --new --continues` or web `continue →` (SessionChain::Links#latest,
922
+ # the walk SessionContinue.run does for `last:`). The chain's end, not the
923
+ # send rule's first live link (Links#first_live): a chain continues only
924
+ # its end, and a schedule never un-archives a retired chain. Both modes use the walk: a
958
925
  # chain continues that link, a same-mode entry queues a turn in it. The
959
926
  # anchor alone is not enough for either: the first continue archives it, so
960
927
  # a same-mode entry read literally would fail "archived" from then on, and
961
928
  # the chain would continue a link that is no longer the end. The anchor is
962
929
  # the fallback when the head is gone (pruned or deleted by hand): the walk
963
- # from it still finds the chain's end.
964
- def target_of(entry, index)
965
- head = index.latest(index.gone?(entry.head) ? entry.anchor : entry.head)
966
- if index.gone?(head)
930
+ # from it still finds the chain's end. An archived end fails (a retired
931
+ # chain stops its schedules), unless a continue of it is in flight
932
+ # (#continuing_reason): then it is a skip, the third member :skip.
933
+ # @return [Array] [target, nil] or [nil, reason] or [nil, reason, :skip]
934
+ def target_of(entry, links)
935
+ head = links.latest(links.gone?(entry.head) ? entry.anchor : entry.head)
936
+ if links.gone?(head)
967
937
  return [nil, entry.mode == CHAIN ? "the chain is gone" : "the session it was made against is gone"]
968
938
  end
969
939
 
970
- return [nil, "archived"] if index.archived?(head)
940
+ if links.archived?(head)
941
+ continuing = continuing_reason(head)
942
+ return continuing ? [nil, continuing, :skip] : [nil, "archived"]
943
+ end
971
944
 
972
945
  [head, nil]
973
946
  end
974
947
 
948
+ # Why an archived +link+ is "not now": a continue of it in flight (a
949
+ # person's `chi send --new --continues` or web `continue →`; ContinueIntent.in_flight:
950
+ # the intent written, the lock held) archived it for a successor this
951
+ # listing doesn't have yet; the next tick's walk reaches it. Else nil. A
952
+ # stale intent (no continue holds the lock) is nil: archived it stays.
953
+ def continuing_reason(link)
954
+ successor = ContinueIntent.in_flight(link, state_dir: @state_dir)
955
+ successor && "being continued as #{successor[0, 8]}; retry at the next tick"
956
+ end
957
+
975
958
  # Which chain an entry belongs to, for the one-firing-per-chain-per-tick
976
959
  # guard: the root of the chain its resolved target is in. Every entry of a
977
- # chain has the same root, whichever link it was added against.
978
- def chain_key(index, entry)
979
- target, _reason = target_of(entry, index)
980
- index.root(target)
960
+ # chain has the same root, whichever link it was added against. One whose
961
+ # target doesn't resolve (gone, archived, being continued) gets a key of
962
+ # its own: it shares no chain with anyone this tick.
963
+ def chain_key(links, entry)
964
+ target, _reason = target_of(entry, links)
965
+ target ? links.root(target) : "unresolved:#{entry.id}"
981
966
  end
982
967
 
983
968
  # Two paths (FR7): a live worker is asked through its Bridge; with no
984
- # worker the files say what the tick can know.
985
- def busy_reason(entry, index, target)
969
+ # worker the files say what the tick can know. A session its owner
970
+ # stopped is a skip first, in both modes: a schedule restarts nothing
971
+ # the owner stopped (deliver_turn would refuse a same-mode firing too,
972
+ # SessionManager::DeliverResult::STOPPED, in the same words).
973
+ def busy_reason(entry, links, target)
986
974
  dir = Session.session_dir(target, state_dir: @state_dir)
987
975
  owner = SessionManager.session_owner(target, state_dir: @state_dir)
988
976
  presence = WorkerPresence.read(target, state_dir: @state_dir, owner: owner, link: :look)
977
+ return [:skip, SessionManager::DeliverResult::STOPPED["detail"]] if presence.stop_marked?
978
+
989
979
  link = presence.link
990
980
 
991
981
  if presence.worker_owned?
@@ -1001,7 +991,7 @@ module Samagotchi
1001
991
  # queues a turn, so for it the files are enough.
1002
992
  return [:skip, "its worker is too old to ask: chi sessions restart #{target[0, 8]}"] if entry.mode == CHAIN
1003
993
 
1004
- return file_busy_reason(index.session(target), dir)
994
+ return file_busy_reason(links.session(target), dir)
1005
995
  end
1006
996
  return [:skip, "its worker is not answering"] if activity.nil?
1007
997
 
@@ -1022,7 +1012,7 @@ module Samagotchi
1022
1012
  # A queued turn is fine: the starting worker takes it.
1023
1013
  return [:skip, "its worker is starting or leaving"] if entry.mode == CHAIN && presence.starting?
1024
1014
 
1025
- file_busy_reason(index.session(target), dir)
1015
+ file_busy_reason(links.session(target), dir)
1026
1016
  end
1027
1017
 
1028
1018
  # The worker's activity snapshot, :old when it has no /activity route, or
@@ -1056,14 +1046,20 @@ module Samagotchi
1056
1046
  nil
1057
1047
  end
1058
1048
 
1059
- def fire_and_record(entry, index)
1060
- outcome = fire(entry, index)
1049
+ # A firing whose target no longer resolves (#target_of: gone, archived,
1050
+ # or being continued since the tick's check): what #check would say.
1051
+ def unresolved(entry, reason, kind)
1052
+ Outcome.new(id: entry.id, title: entry.title, status: kind == :skip ? "skipped" : "failed", detail: reason, entry: entry)
1053
+ end
1054
+
1055
+ def fire_and_record(entry, links)
1056
+ outcome = fire(entry, links)
1061
1057
  record(entry, outcome)
1062
1058
  outcome
1063
1059
  end
1064
1060
 
1065
- def fire(entry, index)
1066
- entry.mode == CHAIN ? fire_chain(entry, index) : fire_same(entry, index)
1061
+ def fire(entry, links)
1062
+ entry.mode == CHAIN ? fire_chain(entry, links) : fire_same(entry, links)
1067
1063
  rescue StandardError => e
1068
1064
  # run_locked re-raises whatever spawn_continuation throws after undoing
1069
1065
  # the move: a spawn failure or an ENOSPC is a failure, not a skip.
@@ -1071,9 +1067,9 @@ module Samagotchi
1071
1067
  Outcome.new(id: entry.id, title: entry.title, status: "failed", detail: "#{e.class}: #{e.message}", entry: entry)
1072
1068
  end
1073
1069
 
1074
- def fire_chain(entry, index)
1075
- head, _reason = target_of(entry, index)
1076
- return Outcome.new(id: entry.id, title: entry.title, status: "failed", detail: "the chain is gone", entry: entry) if head.nil?
1070
+ def fire_chain(entry, links)
1071
+ head, reason, kind = target_of(entry, links)
1072
+ return unresolved(entry, reason, kind) if head.nil?
1077
1073
  # One stored before #add refused it: its link would refuse the line,
1078
1074
  # so it fails here, with no link started and nothing archived.
1079
1075
  if CommandIntake.shell_line?(entry.prompt)
@@ -1099,14 +1095,23 @@ module Samagotchi
1099
1095
  classify(entry, e.reason, e.message)
1100
1096
  end
1101
1097
 
1102
- def fire_same(entry, index)
1103
- target, reason = target_of(entry, index)
1104
- return Outcome.new(id: entry.id, title: entry.title, status: "failed", detail: reason, entry: entry) if target.nil?
1098
+ def fire_same(entry, links, walked_again: false)
1099
+ target, reason, kind = target_of(entry, links)
1100
+ return unresolved(entry, reason, kind) if target.nil?
1105
1101
 
1106
1102
  # Checked again, against the files: a continue made between the tick's
1107
1103
  # listing and this moment archives the target it just resolved to.
1104
+ # One in flight is a skip; one that ended since saved its successor
1105
+ # before it let its intent go, so a fresh listing (one walk again,
1106
+ # checked as the tick checks) finds where the chain went.
1108
1107
  dir = Session.session_dir(target, state_dir: @state_dir)
1109
- return Outcome.new(id: entry.id, title: entry.title, status: "failed", detail: "archived", entry: entry) if ArchiveStore.archived?(dir)
1108
+ if ArchiveStore.archived?(dir)
1109
+ continuing = continuing_reason(target)
1110
+ return fire_same_again(entry) if continuing.nil? && !walked_again
1111
+
1112
+ return Outcome.new(id: entry.id, title: entry.title, status: continuing ? "skipped" : "failed",
1113
+ detail: continuing || "archived", entry: entry)
1114
+ end
1110
1115
  # One stored before #add refused it: the Bridge would refuse it, but a
1111
1116
  # delivery that falls back to the input file is accepted.
1112
1117
  if CommandIntake.shell_line?(entry.prompt)
@@ -1126,12 +1131,25 @@ module Samagotchi
1126
1131
  # one fired into, so the walk survives a link deleted in between.
1127
1132
  Outcome.new(id: entry.id, title: entry.title, status: "pending", detail: "queued a turn",
1128
1133
  entry: entry.with(head: target, pending_session_id: target, pending_turn_id: result.enqueued_id))
1134
+ elsif result.wake_refused?
1135
+ # Stopped (or archived) since the tick's check: a skip, as the check's.
1136
+ Outcome.new(id: entry.id, title: entry.title, status: "skipped", detail: result.detail, entry: entry)
1129
1137
  else
1130
1138
  Outcome.new(id: entry.id, title: entry.title, status: "failed",
1131
1139
  detail: "the turn was not accepted (#{result.status}: #{result.error || result.detail})", entry: entry)
1132
1140
  end
1133
1141
  end
1134
1142
 
1143
+ # #fire_same over a fresh listing: its target and busy checks as the
1144
+ # tick's (#check), then the firing; an end still archived fails.
1145
+ def fire_same_again(entry)
1146
+ links = links_now
1147
+ verdict = check(entry, links)
1148
+ return unresolved(entry, verdict[1], verdict[0]) if verdict
1149
+
1150
+ fire_same(entry, links, walked_again: true)
1151
+ end
1152
+
1135
1153
  def classify(entry, reason, message)
1136
1154
  status = SKIP_REASONS.include?(reason.to_s) ? "skipped" : "failed"
1137
1155
  Outcome.new(id: entry.id, title: entry.title, status: status, detail: message, entry: entry)
@@ -1188,13 +1206,13 @@ module Samagotchi
1188
1206
  # still unarchived: nothing is deleted in that case, and the next firing
1189
1207
  # retries (a schedule failure it is not). The anchor is never pruned:
1190
1208
  # `last:<anchor>` must keep resolving, and it is the id the user remembers.
1191
- def prune(entry, index)
1192
- links = []
1209
+ def prune(entry, links)
1210
+ chain = []
1193
1211
  id = entry.head
1194
1212
  seen = []
1195
1213
  while id && !seen.include?(id)
1196
1214
  seen << id
1197
- links << id
1215
+ chain << id
1198
1216
  # The walk stops at the anchor: the links before it are the user's own
1199
1217
  # history, made before this schedule existed, and the anchor itself is
1200
1218
  # the id `last:<anchor>` and the user remember.
@@ -1202,10 +1220,10 @@ module Samagotchi
1202
1220
 
1203
1221
  # The link a firing just made is not in the tick's listing; every
1204
1222
  # older one is.
1205
- session = index.session(id) || (File.exist?(Session.session_file(id, state_dir: @state_dir)) ? Session.load(id, state_dir: @state_dir) : nil)
1223
+ session = links.session(id) || (File.exist?(Session.session_file(id, state_dir: @state_dir)) ? Session.load(id, state_dir: @state_dir) : nil)
1206
1224
  id = session&.continues
1207
1225
  end
1208
- older = links[entry.keep_links..] || []
1226
+ older = chain[entry.keep_links..] || []
1209
1227
  return if older.empty?
1210
1228
 
1211
1229
  older.reverse_each do |link|
@@ -326,14 +326,18 @@ module Samagotchi
326
326
 
327
327
  # One id at a time, so each line follows the order of the ids given;
328
328
  # two that reach the same link (an old id and its newest link) send
329
- # once.
329
+ # once, also when an old id's send followed a continue (#deliver) to
330
+ # a link named after it: seen is where each one went.
330
331
  seen = {}
331
332
  results = targets(options).map do |target|
332
333
  next unsent(target) unless target.is_a?(SessionInbox::Resolved)
333
334
  next true if seen[target.id]
334
335
 
335
336
  seen[target.id] = true
336
- deliver(target, prompt)
337
+ @sent_to = nil
338
+ sent = deliver(target, prompt)
339
+ seen[@sent_to.id] = true if sent && @sent_to
340
+ sent
337
341
  end
338
342
  results.all? ? 0 : 1
339
343
  ensure
@@ -549,9 +553,11 @@ module Samagotchi
549
553
  return SessionAccess::NewSession.new(**start, continues: options[:continues], model_name: options[:model])
550
554
  end
551
555
 
552
- setup = options[:setup_words] || SessionSetup.new(llm_context: options[:llm_context], thinking: options[:thinking],
553
- toolkit: options[:toolkit_value], settings: options[:settings],
554
- parent_answers: options[:parent_answers])
556
+ # chi send takes no --memory, --mute or --append-system-prompt (a
557
+ # sender's flags, not a terminal's).
558
+ setup = options[:setup_words] || SessionSetup.from_request(llm_context: options[:llm_context], thinking: options[:thinking],
559
+ toolkit: options[:toolkit_value], settings: options[:settings],
560
+ parent_answers: options[:parent_answers])
555
561
  SessionAccess::NewSession.new(**start, working_directory: options[:dir], model_name: options[:model], setup: setup)
556
562
  end
557
563
 
@@ -596,19 +602,28 @@ module Samagotchi
596
602
  # @return [Integer] the exit status
597
603
  def run_wait(prompt, options)
598
604
  target = wait_target(options) or return 1
599
- id = target.id
600
605
  return run_participant_wait(target, prompt, options) if @access.participant?
601
606
 
602
607
  # Local: one read for the check and the baseline; remotely the
603
- # server's wait prepare route reads both (Busy's words).
604
- session = @access.show(id) unless @access.remote?
605
- if (busy = @access.busy(id, queue: @queue, session: session))
606
- error_line("#{target.label} #{busy.message(via: @access.invocation)}")
607
- return 1
608
+ # server's wait prepare route reads both (Busy's words). Again for a
609
+ # link a continue moved the send to (#deliver).
610
+ start = nil
611
+ sent = deliver(target, prompt) do |at|
612
+ session = @access.show(at.id) unless @access.remote?
613
+ if (busy = @access.busy(at.id, queue: @queue, session: session))
614
+ @wait_target = at
615
+ @session_id = at.id
616
+ error_line("#{at.label} #{busy.message(via: @access.invocation)}")
617
+ next false
618
+ end
619
+
620
+ start = @access.prepare_wait(at.id, session: session)
621
+ true
608
622
  end
623
+ return 1 unless sent
609
624
 
610
- start = @access.prepare_wait(id, session: session)
611
- return 1 unless deliver(target, prompt)
625
+ @wait_target = target = @sent_to
626
+ @session_id = id = target.id
612
627
  return report_command(id, label: target.label) if @sent_command
613
628
 
614
629
  target = ReplyWait::Target.message(start, @delivered, queue: @queue)
@@ -759,9 +774,17 @@ module Samagotchi
759
774
  CLI::Exit::OK
760
775
  end
761
776
 
777
+ # A followed send (a head #target resolved) is refused when a continue
778
+ # took its link since (DeliverResult#continued?): it resolves again
779
+ # (#follow_again) and goes to the new link, until CONTINUING_WAIT after
780
+ # the first refusal; the old link is never sent to.
762
781
  # @param target [SessionInbox::Resolved] the session (#target)
763
- # @return [Boolean] whether the message was queued
764
- def deliver(target, prompt)
782
+ # @yieldparam at [SessionInbox::Resolved] each link about to be sent to
783
+ # @yieldreturn [Boolean] false: nothing is sent (its line printed)
784
+ # @return [Boolean] whether the message was queued (@sent_to: where)
785
+ def deliver(target, prompt, deadline: nil, &before)
786
+ return false if block_given? && !yield(target)
787
+
765
788
  id = target.id
766
789
  short = target.label
767
790
  session = @access.show(id)
@@ -783,12 +806,22 @@ module Samagotchi
783
806
  delivery = if @queue then Delivery::QUEUE
784
807
  elsif @cut && running then Delivery::CUT
785
808
  end
786
- result = @access.deliver_turn(id, prompt: prompt, client_id: client_id_for(prompt), images: refs, delivery: delivery)
809
+ result = @access.deliver_turn(id, prompt: prompt, client_id: client_id_for(prompt), images: refs, delivery: delivery,
810
+ follow: target.via != :pinned)
811
+ if result.continued?
812
+ # Copied in before the refusal: not the old link's to keep.
813
+ @access.discard_images(id, refs)
814
+ deadline ||= monotonic + self.class::CONTINUING_WAIT
815
+ again = follow_again(target, deadline)
816
+ return unsent(again) if again.is_a?(Unsent)
817
+ return deliver(again, prompt, deadline: deadline, &before) if again
818
+ end
787
819
  unless result.accepted?
788
820
  @info.puts("#{short} #{result.refusal_text}")
789
821
  return false
790
822
  end
791
823
 
824
+ @sent_to = target
792
825
  @sent_command = result.command?
793
826
  if @sent_command
794
827
  @info.puts("#{short} #{SENT_COMMAND}")
@@ -937,9 +970,9 @@ module Samagotchi
937
970
  def target(given)
938
971
  id = @access.resolve(given)
939
972
  head = @access.head(id)
940
- deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + self.class::CONTINUING_WAIT
973
+ deadline = monotonic + self.class::CONTINUING_WAIT
941
974
  waited = head.continuing?
942
- while head.continuing? && Process.clock_gettime(Process::CLOCK_MONOTONIC) < deadline
975
+ while head.continuing? && monotonic < deadline
943
976
  self.class.pause(self.class::CONTINUING_POLL)
944
977
  head = @access.head(id)
945
978
  end
@@ -951,6 +984,26 @@ module Samagotchi
951
984
  Unsent.new(line: "#{command_name}: #{e.message}", error: true)
952
985
  end
953
986
 
987
+ # +refused+'s id resolved again after a continue took its link
988
+ # (#deliver): #target, pausing between looks while it still names that
989
+ # link, until +deadline+. The new link's worker is the continue's spawn
990
+ # to start (#delivery_note).
991
+ # @return [SessionInbox::Resolved, Unsent, nil] nil: out of time
992
+ def follow_again(refused, deadline)
993
+ while monotonic < deadline
994
+ self.class.pause(self.class::CONTINUING_POLL)
995
+ again = target(refused.asked)
996
+ return again unless again.is_a?(SessionInbox::Resolved)
997
+ next if again.id == refused.id
998
+
999
+ (@continued_here ||= {})[again.id] = true
1000
+ return again
1001
+ end
1002
+ nil
1003
+ end
1004
+
1005
+ def monotonic = Process.clock_gettime(Process::CLOCK_MONOTONIC)
1006
+
954
1007
  # Prints +unsent+'s line. @return [false]
955
1008
  def unsent(unsent)
956
1009
  unsent.error ? error_line(unsent.line) : @info.puts(unsent.line)
@@ -873,8 +873,9 @@ module Samagotchi
873
873
 
874
874
  # Mark a session as stopped (STOPPED_FILE); its session file stays as
875
875
  # it is.
876
+ # @param now [Time] the marker's at (a spec's, the corpus's clock)
876
877
  # @raise [NotFound] when there is no such session
877
- def self.mark_stopped(session_id, state_dir: default_state_dir)
878
+ def self.mark_stopped(session_id, state_dir: default_state_dir, now: Time.now)
878
879
  raise NotFound, session_id unless exist?(session_id, state_dir: state_dir)
879
880
 
880
881
  dir = session_dir(session_id, state_dir: state_dir)
@@ -882,7 +883,7 @@ module Samagotchi
882
883
  # Its own at, on the clock the starting marker's at is written with
883
884
  # (StartingMarker; resume_session compares them): a file's mtime may be
884
885
  # coarse or skewed. Older chi readers ask only whether it exists.
885
- AtomicFile.write(File.join(dir, STOPPED_FILE), JSON.generate({ "at" => Time.now.iso8601(6) }))
886
+ AtomicFile.write(File.join(dir, STOPPED_FILE), JSON.generate({ "at" => now.iso8601(6) }))
886
887
  end
887
888
 
888
889
  # When the stop marker was written: its own at, or (an older chi's empty
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "fileutils"
3
4
  require "socket"
4
5
 
5
6
  require_relative "../session"
@@ -181,15 +182,31 @@ module Samagotchi
181
182
  def upload_images(id, refs, from:)
182
183
  to = session_dir(id)
183
184
  refs.map do |ref|
185
+ target = File.join(to, ref[:file].to_s)
186
+ (@uploaded ||= Set.new) << target unless File.exist?(target)
184
187
  ImageStore.copy_file(ref, from: from, to: to)
185
188
  { file: ref[:file], name: ref[:name] }
186
189
  end
187
190
  end
188
191
 
192
+ # Takes back the copies #upload_images made of +refs+ in the session
193
+ # (a send its delivery refused: chi send's link_continued): only the
194
+ # files it wrote, never one there before (a name is its content's
195
+ # hash, so an earlier turn's image may share it).
196
+ def discard_images(id, refs)
197
+ dir = session_dir(id)
198
+ refs.each do |ref|
199
+ target = File.join(dir, ref[:file].to_s)
200
+ FileUtils.rm_f(target) if @uploaded&.delete?(target)
201
+ end
202
+ end
203
+
189
204
  # @return [SessionManager::DeliverResult]
190
205
  # @raise [SessionManager::OwnedByTUI] a one-turn chi run owns it
191
- def deliver_turn(id, prompt:, client_id:, images:, delivery: nil)
192
- SessionManager.deliver_turn(id, prompt: prompt, client_id: client_id, images: images, delivery: delivery, **dir)
206
+ # @param follow [Boolean] +id+ is the head #head resolved (SessionManager.deliver_turn's follow:)
207
+ def deliver_turn(id, prompt:, client_id:, images:, delivery: nil, follow: false)
208
+ SessionManager.deliver_turn(id, prompt: prompt, client_id: client_id, images: images, delivery: delivery,
209
+ follow: follow, **dir)
193
210
  end
194
211
 
195
212
  # @return [NoteDelivery::Result]