samagotchi 0.178.0 → 0.179.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 (126) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +28 -1
  3. data/docs/architecture.md +4 -2
  4. data/docs/bundles.md +16 -7
  5. data/docs/cli.md +3 -1
  6. data/docs/context.md +25 -1
  7. data/docs/guardrails.md +2 -1
  8. data/docs/internals/attached-context.md +26 -4
  9. data/docs/internals/background-tasks.md +3 -0
  10. data/docs/internals/block-renderers.md +2 -2
  11. data/docs/internals/bridge.md +11 -2
  12. data/docs/internals/bundles.md +63 -34
  13. data/docs/internals/engine.md +1 -1
  14. data/docs/internals/web-frontend.md +18 -1
  15. data/docs/plugins.md +14 -3
  16. data/docs/releasing.md +3 -3
  17. data/docs/scheduling.md +4 -0
  18. data/docs/sessions.md +8 -2
  19. data/docs/testing.md +4 -1
  20. data/lib/samagotchi/block_renderers.rb +12 -14
  21. data/lib/samagotchi/bootstrap/bundles.rb +2 -2
  22. data/lib/samagotchi/bootstrap_command.rb +1 -1
  23. data/lib/samagotchi/bridge/card_wait.rb +34 -0
  24. data/lib/samagotchi/bridge/turn_accumulator.rb +22 -4
  25. data/lib/samagotchi/bundle_command/check.rb +10 -10
  26. data/lib/samagotchi/bundle_command/installed_check.rb +2 -2
  27. data/lib/samagotchi/bundle_command/try/sandbox.rb +3 -3
  28. data/lib/samagotchi/bundle_command.rb +17 -17
  29. data/lib/samagotchi/bundle_manifest.rb +579 -0
  30. data/lib/samagotchi/bundle_needs.rb +9 -8
  31. data/lib/samagotchi/bundle_settings_check.rb +9 -8
  32. data/lib/samagotchi/bundles/claude-peer/manifest.yml +5 -3
  33. data/lib/samagotchi/bundles/claude-peer/plugin.rb +4 -4
  34. data/lib/samagotchi/bundles/claude-peer/scripts/chi-peer-SKILL.md +11 -6
  35. data/lib/samagotchi/bundles/codex-peer/manifest.yml +5 -3
  36. data/lib/samagotchi/bundles/codex-peer/plugin.rb +4 -3
  37. data/lib/samagotchi/bundles/codex-peer/scripts/chi-peer-SKILL.md +11 -6
  38. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  39. data/lib/samagotchi/bundles/system/memory_guide.md +1 -1
  40. data/lib/samagotchi/config.rb +2 -2
  41. data/lib/samagotchi/context_absorber.rb +36 -6
  42. data/lib/samagotchi/context_note.rb +8 -5
  43. data/lib/samagotchi/context_providers.rb +30 -27
  44. data/lib/samagotchi/context_sources.rb +42 -12
  45. data/lib/samagotchi/engine/messages.rb +1 -1
  46. data/lib/samagotchi/events.rb +6 -5
  47. data/lib/samagotchi/guardrail_wiring.rb +20 -21
  48. data/lib/samagotchi/guardrails/approval.rb +3 -2
  49. data/lib/samagotchi/guardrails/outside.rb +3 -3
  50. data/lib/samagotchi/{memory_bundle → installed_bundles}/bundle_hook.rb +1 -1
  51. data/lib/samagotchi/installed_bundles/dir.rb +129 -0
  52. data/lib/samagotchi/{memory_bundle → installed_bundles}/file_digest.rb +1 -1
  53. data/lib/samagotchi/{memory_bundle → installed_bundles}/file_standing.rb +2 -2
  54. data/lib/samagotchi/{memory_bundle/installed_manifest.rb → installed_bundles/manifest.rb} +21 -21
  55. data/lib/samagotchi/{memory_bundle → installed_bundles}/plugin_ref.rb +2 -2
  56. data/lib/samagotchi/{memory_bundle/installed_bundle.rb → installed_bundles/record.rb} +17 -17
  57. data/lib/samagotchi/installed_bundles/sha.rb +41 -0
  58. data/lib/samagotchi/installed_bundles/standing.rb +45 -0
  59. data/lib/samagotchi/installed_bundles.rb +90 -0
  60. data/lib/samagotchi/memory_bundle/asset_installer.rb +7 -7
  61. data/lib/samagotchi/memory_bundle/builder.rb +13 -13
  62. data/lib/samagotchi/memory_bundle/file_state.rb +9 -9
  63. data/lib/samagotchi/memory_bundle/installed_copy.rb +6 -6
  64. data/lib/samagotchi/memory_bundle/installer.rb +33 -33
  65. data/lib/samagotchi/memory_bundle/listing.rb +5 -5
  66. data/lib/samagotchi/memory_bundle/manifest_standing.rb +7 -7
  67. data/lib/samagotchi/memory_bundle/merger.rb +15 -15
  68. data/lib/samagotchi/memory_bundle/profile.rb +8 -8
  69. data/lib/samagotchi/memory_bundle/provenance.rb +59 -192
  70. data/lib/samagotchi/memory_bundle/remerge.rb +16 -16
  71. data/lib/samagotchi/memory_bundle/shas.rb +2 -2
  72. data/lib/samagotchi/memory_bundle/shipped_history.rb +1 -1
  73. data/lib/samagotchi/memory_bundle/shipped_update.rb +17 -17
  74. data/lib/samagotchi/memory_bundle/status.rb +15 -15
  75. data/lib/samagotchi/memory_bundle/system_bundle.rb +12 -12
  76. data/lib/samagotchi/memory_bundle/trash.rb +2 -2
  77. data/lib/samagotchi/memory_bundle/uninstaller.rb +8 -8
  78. data/lib/samagotchi/memory_bundle.rb +2 -2
  79. data/lib/samagotchi/memory_command.rb +4 -4
  80. data/lib/samagotchi/{memory_bundle → memory_index}/entry_size.rb +8 -8
  81. data/lib/samagotchi/{memory_bundle/index_size.rb → memory_index/size.rb} +6 -6
  82. data/lib/samagotchi/{memory_bundle/index_sync.rb → memory_index/sync.rb} +5 -5
  83. data/lib/samagotchi/{memory_bundle/index_updater.rb → memory_index/updater.rb} +2 -2
  84. data/lib/samagotchi/memory_usage.rb +5 -5
  85. data/lib/samagotchi/muted_memories.rb +1 -1
  86. data/lib/samagotchi/peer_exchanges.rb +76 -0
  87. data/lib/samagotchi/plugin/context.rb +4 -0
  88. data/lib/samagotchi/plugin/loader.rb +35 -33
  89. data/lib/samagotchi/plugin/peer.rb +42 -11
  90. data/lib/samagotchi/project_subfolders.rb +9 -9
  91. data/lib/samagotchi/reply_wait/target.rb +11 -4
  92. data/lib/samagotchi/self_report.rb +14 -14
  93. data/lib/samagotchi/session_access/local.rb +16 -1
  94. data/lib/samagotchi/session_access/remote.rb +2 -1
  95. data/lib/samagotchi/session_config.rb +23 -19
  96. data/lib/samagotchi/session_manager/running_tasks.rb +15 -2
  97. data/lib/samagotchi/session_retention.rb +13 -4
  98. data/lib/samagotchi/session_stores.rb +3 -0
  99. data/lib/samagotchi/system_prompt.rb +4 -4
  100. data/lib/samagotchi/terminal_ui/attach_launcher.rb +5 -1
  101. data/lib/samagotchi/terminal_ui/formatting.rb +2 -2
  102. data/lib/samagotchi/terminal_ui/model_segments_text.rb +5 -5
  103. data/lib/samagotchi/terminal_ui.rb +4 -1
  104. data/lib/samagotchi/testing/bundle.rb +3 -3
  105. data/lib/samagotchi/testing/install.rb +3 -3
  106. data/lib/samagotchi/testing/sandbox.rb +2 -2
  107. data/lib/samagotchi/tool_runner.rb +14 -14
  108. data/lib/samagotchi/tools/memory.rb +22 -22
  109. data/lib/samagotchi/update_command.rb +4 -4
  110. data/lib/samagotchi/version.rb +1 -1
  111. data/lib/samagotchi/web/app.rb +14 -1
  112. data/lib/samagotchi/web/message_display.rb +6 -0
  113. data/lib/samagotchi/web/participant_view.rb +1 -1
  114. data/lib/samagotchi/web/proxy_gate.rb +1 -0
  115. data/lib/samagotchi/web/public/card_kinds.js +8 -3
  116. data/lib/samagotchi/web/public/cards_place.js +15 -1
  117. data/lib/samagotchi/web/public/ctx.js +1 -1
  118. data/lib/samagotchi/web/public/history_shape.js +3 -0
  119. data/lib/samagotchi/web/public/turn_block.js +46 -8
  120. data/lib/samagotchi/web/public/turn_settle.js +117 -0
  121. data/lib/samagotchi/web/push/notifier.rb +2 -2
  122. data/lib/samagotchi/web/session_access_routes.rb +21 -1
  123. data/lib/samagotchi/web/session_hub.rb +20 -4
  124. data/lib/samagotchi/worker_boot.rb +4 -1
  125. metadata +19 -12
  126. data/lib/samagotchi/memory_bundle/manifest.rb +0 -581
@@ -329,6 +329,7 @@ module Samagotchi
329
329
  ["POST", %r{\A/api/sessions/([^/]+)/images\z}, :handle_image_upload, :participant, :session],
330
330
  ["GET", %r{\A/api/sessions/([^/]+)/images/([^/]+)\z}, :handle_image, :participant, :session],
331
331
  ["GET", %r{\A/api/sessions/([^/]+)/context\z}, :handle_context_list, :owner, :session],
332
+ ["GET", %r{\A/api/sessions/([^/]+)/peers\z}, :handle_peers, :owner, :session],
332
333
  ["GET", %r{\A/api/sessions/([^/]+)/context/([^/]+)\z}, :handle_context_show, :owner, :session],
333
334
  ["POST", %r{\A/api/sessions/([^/]+)/context\z}, :handle_context_add, :owner, :session],
334
335
  ["POST", %r{\A/api/sessions/([^/]+)/context/([^/]+)/push\z}, :handle_context_push, :owner, :session],
@@ -1010,7 +1011,7 @@ module Samagotchi
1010
1011
 
1011
1012
  root = dir && ProjectScope.root_for(dir)
1012
1013
  # Lazy retention sweep (once per 24h)
1013
- Degrade.call(:web, "retention_sweep_failed") { @manager.retention_sweep_if_due(state_dir: @state_dir) }
1014
+ @hub.sweep_if_due
1014
1015
  limit = sanitize_limit(req.GET["limit"])
1015
1016
  offset = sanitize_offset(req.GET["offset"])
1016
1017
  all = @hub.snapshot(project_root: root, sort: sanitize_sort(req.GET["sort"]), order: sanitize_order(req.GET["order"]))
@@ -1443,6 +1444,7 @@ module Samagotchi
1443
1444
  state_dir: default_state_dir)
1444
1445
  .map { |candidate, status| candidate.to_h.merge("name" => candidate.name, "status" => status) }
1445
1446
  end
1447
+
1446
1448
  json_response(200, body)
1447
1449
  end
1448
1450
 
@@ -1581,11 +1583,22 @@ module Samagotchi
1581
1583
  why: source.why, hint: snapshot.hint || source.hint, summary: snapshot.summary, error: snapshot.error,
1582
1584
  fetched_at: snapshot.fetched_at, has_text: snapshot.text?, muted: own.muted?(source.name),
1583
1585
  unread: snapshot.text? && subs[source.name]&.read != snapshot.revision }
1586
+ row.merge!(context_peer(attached))
1584
1587
  return row unless full
1585
1588
 
1586
1589
  row.merge(source: source.to_h, snapshot: snapshot.to_h.except("text", :text), shadowed: attached.shadowed)
1587
1590
  end
1588
1591
 
1592
+ # A pushed session source named <peer>-inbox / -outbox: the pairing's
1593
+ # peer ("claude"), its leg and label, by name (docs/context.md, Peer
1594
+ # sources); {} for any other.
1595
+ def context_peer(attached)
1596
+ return {} unless attached.source.push? && attached.location.session?
1597
+
1598
+ peer, leg = ContextSources.peer_leg(attached.name)
1599
+ peer ? { peer: peer, leg: leg, label: ContextSources.peer_label(peer) } : {}
1600
+ end
1601
+
1589
1602
  def handle_stream(req, id)
1590
1603
  # Validate session exists
1591
1604
  begin
@@ -123,6 +123,12 @@ module Samagotchi
123
123
  content = (m[:content] || m["content"]).to_s
124
124
  if Samagotchi::ContextNote.note?(m)
125
125
  note = { role: "note", content: Samagotchi::ContextNote.text_of(m), label: Samagotchi::ContextNote.label_of(m), **time_of(m) }
126
+ # The chip it is about and, for a peer's answer, whose (as the
127
+ # live :context_added carries them).
128
+ context_source = Samagotchi::ContextNote.fetch(m, :context_source)
129
+ note[:context_source] = context_source.to_s if context_source
130
+ peer = Samagotchi::ContextNote.fetch(m, :peer)
131
+ note[:peer] = peer if peer.is_a?(Hash)
126
132
  payload = Samagotchi::ContextNote.fetch(m, :objectives)
127
133
  entry = payload && Samagotchi::Objectives.entry(payload, before: objectives)
128
134
  if entry
@@ -86,7 +86,7 @@ module Samagotchi
86
86
  after_generation after_tool_call after_turn answer_display before_generation before_tool_call before_turn
87
87
  card command_output command_queued command_ran context_added empty_answer_retry
88
88
  generation_cancelled generation_progress generation_started guardrail_warning hook_notice
89
- llm_context_edited merged_input objectives_updated participants_changed pending_input_merged plugin_init_finished
89
+ llm_context_edited merged_input objectives_updated part_settled participants_changed pending_input_merged plugin_init_finished
90
90
  plugin_init_started plugin_init_wait question question_relay reasoning_history_refused
91
91
  recap_ready reminder_injected sampling_refused session_end session_start side_usage steer_cut thinking_dropped
92
92
  thinking_refused tool_dispatch_completed tool_dispatch_started used_memories_updated
@@ -124,6 +124,7 @@ module Samagotchi
124
124
 
125
125
  return proxy_refuse(req, "owner token with identity #{shown}#{identity_hint(req)}")
126
126
  end
127
+ require_relative "../grants"
127
128
  grant_tokens = given.select { |value| Grants.token?(value) }
128
129
  return proxy_refuse(req, "no token (identity #{shown})") if grant_tokens.empty?
129
130
 
@@ -34,9 +34,14 @@ export function continueWait() {
34
34
  }
35
35
 
36
36
  // A plugin card's wait: a running turn's card with an action asks (as
37
- // check-in's), a warning stays in sight; null: it doesn't wait.
38
- export function cardWait(card) {
39
- const asks = !!card?.in_turn && (card.actions || []).some((a) => a && a.command);
37
+ // check-in's), a warning stays in sight; null: it doesn't wait. The one rule
38
+ // cards_place.js upsertCard and turn_block.js drawnTurnNodes ask; the DOM
39
+ // readers (stage_cards.js, stage_waiting.js waitingKind, card.js
40
+ // isNoticeCard) stay the cross-check. +inTurn+ overrides the card's own
41
+ // in_turn: a caller that already knows the card's turn (a drawing's card, an
42
+ // update of a card already shown, which asks by its actions alone).
43
+ export function cardWait(card, { inTurn = !!card?.in_turn } = {}) {
44
+ const asks = inTurn && (card?.actions || []).some((a) => a && a.command);
40
45
  return { kind: asks ? "asks" : card?.level === "warn" ? "warn" : null, approval: false, summary: String(card?.title || "") };
41
46
  }
42
47
 
@@ -73,7 +73,9 @@ export function createCardsPlace({
73
73
  if (!card || !card.id) return;
74
74
  turnDom.settleFold?.();
75
75
  const existing = cardElement(card.id);
76
- const asks = (card.actions || []).some((a) => a && a.command);
76
+ // Asking by its actions alone: an update of a card shown between turns
77
+ // with actions counts as asking (it settles nothing on the stage).
78
+ const asks = cardWait(card, { inTurn: true }).kind === "asks";
77
79
  if (existing) {
78
80
  const wasWarn = existing.classList.contains("warn");
79
81
  const drawn = drawCard(existing, card);
@@ -122,6 +124,9 @@ export function createCardsPlace({
122
124
  else if (entry.in_turn) placeTurnNotice(entry, before);
123
125
  else if (entry.type === "hook_notice") bubbles.showHookNotice(entry, { before });
124
126
  }
127
+ // A drawn turn's question slot whose question never came (CardStore
128
+ // dropped it, a pending one): nothing in its place.
129
+ historyEl.querySelectorAll("[data-question-slot]").forEach((slot) => slot.remove());
125
130
  }
126
131
 
127
132
  // An in-turn entry (not a question) of a turn the history drew from its
@@ -179,6 +184,15 @@ export function createCardsPlace({
179
184
  const card = questionCards.questionCard();
180
185
  if (!card || card.dataset.qid !== String(pq.id)) return;
181
186
  questionCards.resolveQuestion(pq.id, { answer: entry.answer || null, cancelled: !!entry.cancelled, reason: entry.reason || "" });
187
+ // A drawn turn keeps its place (turn_block.js drawnTurnNodes, the order
188
+ // live left it in: turn_settle.js); an undrawn one (an old drawing
189
+ // without question events) goes before the later lines and the answer.
190
+ const slot = turnEls.find((el) => el.dataset.questionSlot === String(pq.id));
191
+ if (slot) {
192
+ if (slot.dataset.drawn) card.dataset.drawn = slot.dataset.drawn;
193
+ slot.replaceWith(card);
194
+ return;
195
+ }
182
196
  const later = turnEls.find((el) => el.matches(".bubble.user.steered") && Number(el.dataset.step) > asked);
183
197
  historyEl.insertBefore(card, later || turnAnswerEl(turnEls) || before);
184
198
  }
@@ -90,7 +90,7 @@ function count(n) {
90
90
  }
91
91
 
92
92
  // A token count as the size readouts word it: "450", "2.0k". As
93
- // MemoryBundle::IndexSize.count_text.
93
+ // MemoryIndex::Size.count_text.
94
94
  function countK(n) {
95
95
  return n >= 1000 ? `${(Math.round(n / 100) / 10).toFixed(1)}k` : String(Math.round(n));
96
96
  }
@@ -148,6 +148,9 @@ function childItems(el) {
148
148
  if (el.matches(".turn-timing")) return [item("timing", textOf(el))];
149
149
  if (el.matches(".bubble.cancel")) return [item(el.classList.contains("stopped") ? "cancel" : "failed", textOf(el))];
150
150
  if (el.matches(".bubble.question")) return [questionItem(el)];
151
+ // A drawn turn's question before its card came (turn_block.js
152
+ // questionSlot): a question (reload_check.js drops them with the cards).
153
+ if (el.matches("[data-question-slot]")) return [item("question")];
151
154
  if (el.matches(".plugin-card")) return [cardItem(el)];
152
155
  if (el.matches(".steer-row")) return [item("steer", textOf(el.querySelector("summary")))];
153
156
  return [otherItem(el)];
@@ -29,6 +29,7 @@ import { answerRefsOf, setAnswerRefs } from "./answer_refs.js";
29
29
  import { bindRowRefs } from "./refs.js";
30
30
  import { openAfterEnd } from "./block_open.js";
31
31
  import { drawCard, isNoticeCard, leavesBlock, shownElsewhere } from "./card.js";
32
+ import { settleOrder } from "./turn_settle.js";
32
33
  import { routeChunk } from "./chunk_router.js";
33
34
  import { drawCommandBubble } from "./commands.js";
34
35
  import { endBubbleTemplate } from "./bubbles.js";
@@ -842,6 +843,30 @@ function drawnCardEl(event, cards) {
842
843
  return el;
843
844
  }
844
845
 
846
+ // A drawn turn's question, before its card is placed (cards_place.js
847
+ // placeResolvedQuestion replaces it; placeSnapshotCards drops one whose
848
+ // question never came).
849
+ function questionSlot(id) {
850
+ const el = document.createElement("div");
851
+ el.className = "question-slot";
852
+ el.dataset.questionSlot = String(id);
853
+ return el;
854
+ }
855
+
856
+ // +pieces+ (turn_settle.js settleOrder) as their entries, with each +loose+
857
+ // card (one that waited later, or no step took) before the first piece that
858
+ // arrived after it.
859
+ function placedPieces(pieces, els, loose) {
860
+ const out = [];
861
+ const rest = [...loose];
862
+ for (const piece of pieces) {
863
+ while (rest.length && rest[0].at < piece.at) out.push(rest.shift().entry);
864
+ const entry = els.get(piece.at);
865
+ if (entry) out.push(entry);
866
+ }
867
+ return [...out, ...rest.map((x) => x.entry)];
868
+ }
869
+
845
870
  // A drawn turn's pieces (+group+: turnGroups' drawn group, its drawing
846
871
  // {events, end}), drawn by the live turn block itself: its events go
847
872
  // through the block's own handlers as the stream handlers send them live
@@ -869,10 +894,15 @@ function drawnTurnNodes(group, items, { thumbs, capabilities = {}, cards = null
869
894
  },
870
895
  });
871
896
  const merged = [...(group.merged || [])];
897
+ // What live put beside the block, in the order it left (turn_settle.js):
898
+ // each piece's element by its event's index; a loose card (no step took it).
899
+ const settled = settleOrder(events);
900
+ const pieceEls = new Map();
901
+ const loose = [];
872
902
  // The ✂ marks a strategy saved on the turn's outputs since (its items'
873
903
  // marks, by output id): an overlay on the rows, as a reload's.
874
904
  const marks = Object.assign({}, ...items.filter((it) => it?.drawn === group.drawn && it.marks).map((it) => it.marks));
875
- for (const event of events) {
905
+ for (const [at, event] of events.entries()) {
876
906
  switch (event?.type) {
877
907
  case "turn_started": view.turnStarted(event); break;
878
908
  case "generation_started": view.generationStarted(event, null); break;
@@ -885,28 +915,36 @@ function drawnTurnNodes(group, items, { thumbs, capabilities = {}, cards = null
885
915
  case "steer_cut": view.notice({ line: steerCutLine(event), cls: "steer-cut" }); break;
886
916
  case "llm_context_edited": view.notice(llmContextNotice(event)); break;
887
917
  case "pending_input_merged": (event.steers || []).forEach((steer) => view.steer(steer)); break;
888
- case "merged_input": extras.push({ merged: merged.shift() ?? null }); break;
918
+ case "merged_input": pieceEls.set(at, { merged: merged.shift() ?? null }); break;
889
919
  case "reminder_injected": {
890
920
  const el = document.createElement("div");
891
921
  drawCommandBubble(el, { label: null, line: reminderText(event), text: "" });
892
922
  const when = fullTime(event.at);
893
923
  if (when) el.title = when;
894
- extras.push({ el });
924
+ pieceEls.set(at, { el });
895
925
  break;
896
926
  }
897
927
  case "card": {
898
- // Live: a card that asks (its actions run commands) or warns stays
899
- // in sight beside the block (cards_place.js upsertCard, the
900
- // stage's card); any other is a row of its step.
928
+ // Live: a card that waited when it arrived (it asked, or warned)
929
+ // stays in sight beside the block (cards_place.js upsertCard, the
930
+ // stage's card) until it leaves (turn_settle.js); any other is a row
931
+ // of its step. Kept with the block's when it still warns: read off
932
+ // the drawn element (CardStore's latest).
901
933
  const el = drawnCardEl(event, cards);
902
- const asks = (event.actions || []).some((a) => a && a.command);
903
934
  const warn = el.classList.contains("warn");
904
- if (asks || warn || !view.card(el)) extras.push({ el, warn });
935
+ if (settled.cards.has(at)) pieceEls.set(at, { el, warn });
936
+ else if (warn || !view.card(el)) loose.push({ at, entry: { el, warn } });
905
937
  break;
906
938
  }
907
939
  default: break;
908
940
  }
909
941
  }
942
+ // A question is an empty slot: cards_place.js placeResolvedQuestion puts
943
+ // the answered card there.
944
+ for (const piece of settled.pieces) {
945
+ if (piece.kind === "question") pieceEls.set(piece.at, { el: questionSlot(piece.id) });
946
+ }
947
+ extras.push(...placedPieces(settled.pieces, pieceEls, loose));
910
948
  const empty = kind === "completed" && (group.emptyAnswer != null || end.turn_summary?.empty_answer);
911
949
  const endNote = empty ? elementOf(emptyAnswerTemplate(group.emptyAnswer != null ? items[group.emptyAnswer] : end.turn_summary.empty_answer)) : null;
912
950
  // The answer's key (data-answer-turn: Revise, the fold) is the turn's own
@@ -0,0 +1,117 @@
1
+ // A finished turn's pieces beside its block, in the order live left them
2
+ // there (turn_block.js drawnTurnNodes builds its extras from it). Live, the
3
+ // stage's extras go to the history while the turn is opened there (a docking
4
+ // piece opened it: a question asked, a card that asks), each when it stops
5
+ // waiting (stage_asking.js settleCards, stage_view.js settleWaiting), and
6
+ // the rest at the hand-off, in their order:
7
+ // - a reminder or a merged line: where it arrived (it never waits);
8
+ // - a question with a lead-in (its step's text became its "said" bubble):
9
+ // at its request, where the lead-in went (stage_opened.js ask);
10
+ // - a question without one: at its answer (or its cancel);
11
+ // - a card that waited when it arrived (an asking card, a warning): where
12
+ // it stopped waiting (the drawing's part_settled, Bridge::TurnAccumulator
13
+ // #fold_card), while the turn is opened; else at the hand-off. One still
14
+ // waiting at the end goes last (a warning there leaves with the block's
15
+ // kept cards: drawnTurnNodes reads that off the drawn card).
16
+ // A card that didn't wait at arrival is a row of its step: not a piece. Its
17
+ // arrival wait is the first part_settled's `was` (the drawing keeps the
18
+ // card's latest version only), else its event's own; a drawing written
19
+ // before settle parts orders its cards by their latest version.
20
+ // Pure: no DOM. docs/internals/web-frontend.md (A drawn turn).
21
+ import { cardWait } from "./card_kinds.js";
22
+
23
+ // Whether each question has a lead-in, as cards_place.js
24
+ // placeResolvedQuestion decides it on a reload: its step has text, and it
25
+ // is that step's first question. @return Map<question id, boolean>
26
+ function leadIns(events) {
27
+ const text = new Map();
28
+ let step = 0;
29
+ for (const e of events) {
30
+ if (e?.type === "generation_started") step = Number(e.iteration) || step + 1;
31
+ else if (e?.type === "generation_chunk" && e.text) text.set(step, (text.get(step) || "") + e.text);
32
+ }
33
+ const out = new Map();
34
+ const taken = new Set();
35
+ step = 0;
36
+ for (const e of events) {
37
+ if (e?.type === "generation_started") step = Number(e.iteration) || step + 1;
38
+ if (e?.type !== "question_requested" || e.pending_question?.id == null) continue;
39
+ const has = !taken.has(step) && !!(text.get(step) || "").trim();
40
+ if (has) taken.add(step);
41
+ out.set(String(e.pending_question.id), has);
42
+ }
43
+ return out;
44
+ }
45
+
46
+ // +events+: a drawing's events (chi web's turn_drawings[id].events).
47
+ // @return {pieces: [{at, kind: "card" | "question" | "merged" | "reminder", id?}], cards: Set<at>}
48
+ // pieces: in live's order (+at+: its event's index; a question's is its
49
+ // question_requested); cards: the card events that are pieces (the others
50
+ // are rows of their step)
51
+ export function settleOrder(events = []) {
52
+ const list = Array.isArray(events) ? events : [];
53
+ const arrival = new Map();
54
+ for (const e of list) {
55
+ if (e?.type === "part_settled" && e.of === "card" && e.id != null && !arrival.has(String(e.id))) arrival.set(String(e.id), e.was || null);
56
+ }
57
+ const lead = leadIns(list);
58
+ const stage = [];
59
+ const out = [];
60
+ const cards = new Map();
61
+ const questions = new Map();
62
+ let opened = false;
63
+ const leave = () => {
64
+ if (!opened) return;
65
+ for (let i = 0; i < stage.length;) {
66
+ if (stage[i].waits) i += 1;
67
+ else out.push(stage.splice(i, 1)[0].piece);
68
+ }
69
+ };
70
+ list.forEach((e, at) => {
71
+ switch (e?.type) {
72
+ case "merged_input": stage.push({ piece: { at, kind: "merged" }, waits: false }); break;
73
+ case "reminder_injected": stage.push({ piece: { at, kind: "reminder" }, waits: false }); break;
74
+ case "card": {
75
+ const id = String(e.id ?? "");
76
+ if (cards.has(id)) break;
77
+ const wait = arrival.has(id) ? arrival.get(id) : cardWait(e, { inTurn: true }).kind;
78
+ if (!wait) break;
79
+ const entry = { piece: { at, kind: "card", id }, waits: true };
80
+ cards.set(id, entry);
81
+ stage.push(entry);
82
+ if (wait === "asks") opened = true;
83
+ break;
84
+ }
85
+ case "part_settled": {
86
+ const entry = e.of === "card" ? cards.get(String(e.id ?? "")) : null;
87
+ if (entry) entry.waits = !!e.now;
88
+ break;
89
+ }
90
+ case "question_requested": {
91
+ const id = e.pending_question?.id;
92
+ if (id == null || questions.has(String(id))) break;
93
+ // The turn opens first (stage_asking.js openTurn: what the extras
94
+ // held goes to the history), then the lead-in goes to the
95
+ // history's end; the answered card lands under it.
96
+ opened = true;
97
+ leave();
98
+ const entry = { piece: { at, kind: "question", id: String(id) }, waits: true };
99
+ questions.set(String(id), entry);
100
+ if (lead.get(String(id))) out.push(entry.piece);
101
+ else stage.push(entry);
102
+ break;
103
+ }
104
+ case "question_answered":
105
+ case "question_cancelled": {
106
+ const entry = questions.get(String(e.id ?? ""));
107
+ if (entry) entry.waits = false;
108
+ break;
109
+ }
110
+ default: break;
111
+ }
112
+ leave();
113
+ });
114
+ // The hand-off: what is still in the stage, in its order.
115
+ out.push(...stage.map((entry) => entry.piece));
116
+ return { pieces: out, cards: new Set([...cards.values()].map((entry) => entry.piece.at)) };
117
+ }
@@ -5,7 +5,7 @@ require "uri"
5
5
  require "time"
6
6
  require_relative "attention"
7
7
  require_relative "../../log"
8
- require_relative "../../memory_bundle/file_standing"
8
+ require_relative "../../installed_bundles/file_standing"
9
9
 
10
10
  module Samagotchi
11
11
  module Web
@@ -82,7 +82,7 @@ module Samagotchi
82
82
 
83
83
  # " Merged the update into 1 file you edited. 2 files stay behind." ("" for none).
84
84
  def self.file_words(notes)
85
- words = MemoryBundle::FileStanding.counts_sentence(merged: notes[:merged].to_i, behind: notes[:kept].to_i)
85
+ words = InstalledBundles::FileStanding.counts_sentence(merged: notes[:merged].to_i, behind: notes[:kept].to_i)
86
86
  words.empty? ? "" : " #{words}"
87
87
  end
88
88
 
@@ -6,6 +6,7 @@ require_relative "../session_inbox"
6
6
  require_relative "../reply_wait"
7
7
  require_relative "../pending_question"
8
8
  require_relative "../context_sources"
9
+ require_relative "../peer_exchanges"
9
10
  require_relative "../context_command"
10
11
  require_relative "../send_command"
11
12
  require_relative "../launch_mode"
@@ -457,6 +458,25 @@ module Samagotchi
457
458
  error_response(400, "note_rejected", e.message)
458
459
  end
459
460
 
461
+ # GET /api/sessions/:id/peers: the owner's peer exchanges from files.
462
+ def handle_peers(_req, id)
463
+ @session_class.load(id, state_dir: default_state_dir)
464
+ own = ContextSources.session_location(id, state_dir: default_state_dir)
465
+ entries = PeerExchanges.read(id, state_dir: default_state_dir).group_by { |entry| entry["peer"] }
466
+ peers = {}
467
+ own.sources.each do |source|
468
+ next unless source.push?
469
+
470
+ peer, leg = ContextSources.peer_leg(source.name)
471
+ next unless peer
472
+
473
+ row = (peers[peer] ||= { name: peer, label: ContextSources.peer_label(peer), inbox: false, outbox: false })
474
+ row[leg.to_sym] = true
475
+ end
476
+ peers.each_value { |row| row[:exchanges] = PeerExchanges.joined(entries.fetch(row[:name], [])) }
477
+ json_response(200, { peers: peers.values })
478
+ end
479
+
460
480
  # POST /api/sessions/:id/context/:name/push {text, summary, wake,
461
481
  # hint}: new text for the session's --push source (chi context push;
462
482
  # the fields as a source's JSON output gives them, checked the same
@@ -471,7 +491,7 @@ module Samagotchi
471
491
  return error_response(400, "missing_fields", "text is required") unless body["text"].is_a?(String)
472
492
 
473
493
  fetched = begin
474
- ContextSources.parse_output(JSON.generate(body.slice("text", "summary", "wake", "hint")))
494
+ ContextSources.parse_output(JSON.generate(body.slice("text", "summary", "wake", "hint", "re")))
475
495
  rescue ContextSources::Invalid => e
476
496
  return error_response(400, "invalid_text", e.message)
477
497
  end
@@ -47,6 +47,7 @@ module Samagotchi
47
47
  # opened an old session without saving it has no file signal until its first save).
48
48
  FULL_PROBE_INTERVAL = 10.0
49
49
  SCHEDULE_TICK_STOP_WAIT = 5.0
50
+ SWEEP_STOP_WAIT = 5.0
50
51
 
51
52
  # What a subscriber gets: `session` with {session: summary} for an
52
53
  # upsert, `session_gone` with {id:} for a removal, `chi` with
@@ -111,6 +112,7 @@ module Samagotchi
111
112
  @next_schedule_tick = nil
112
113
  @schedule_tick_in_flight = false
113
114
  @schedule_tick_thread = nil
115
+ @sweep_thread = nil
114
116
  @wakeup = Queue.new # stop wakes the tick thread out of its sleep
115
117
  @thread = nil
116
118
  @stopped = false
@@ -135,6 +137,8 @@ module Samagotchi
135
137
  thread&.join(@scan_interval + 1.0)
136
138
  schedule_thread = @monitor.synchronize { @schedule_tick_thread }
137
139
  schedule_thread&.join(SCHEDULE_TICK_STOP_WAIT)
140
+ sweep_thread = @monitor.synchronize { @sweep_thread }
141
+ sweep_thread&.join(SWEEP_STOP_WAIT)
138
142
  nil
139
143
  end
140
144
 
@@ -147,21 +151,33 @@ module Samagotchi
147
151
  # gives the retention sweep its chance (it used to run on
148
152
  # GET /api/sessions, which the page no longer calls).
149
153
  def scan
150
- @monitor.synchronize do
154
+ full = @monitor.synchronize do
151
155
  full = full_probe_due?
152
156
  SessionContinue.repair_interrupted(state_dir: @state_dir)
153
157
  scan_files
154
158
  @sessions.each_key { |id| refresh(id, probe: full) }
155
159
  if full
156
- sweep
157
160
  check_installed
158
161
  end
162
+ full
159
163
  end
164
+ sweep_if_due if full
160
165
  # Outside the projection's lock: a firing can wait for a recap.
161
166
  schedule_tick
162
167
  nil
163
168
  end
164
169
 
170
+ # Launch at most one sweep; neither projection readers nor requests
171
+ # wait for its per-session task stops.
172
+ def sweep_if_due
173
+ @monitor.synchronize do
174
+ return if @stopped || @sweep_thread&.alive?
175
+
176
+ @sweep_thread = Thread.new { sweep }
177
+ end
178
+ nil
179
+ end
180
+
165
181
  # The newest installed chi as of the last full probe (nil: unknown).
166
182
  def installed
167
183
  @monitor.synchronize { @installed }
@@ -337,8 +353,8 @@ module Samagotchi
337
353
 
338
354
  def sweep
339
355
  @manager.retention_sweep_if_due(state_dir: @state_dir)
340
- rescue StandardError
341
- nil
356
+ rescue StandardError => e
357
+ Log.warn(:web, "retention_sweep_failed", error: e.class.name, msg: e.message)
342
358
  end
343
359
 
344
360
  # chi web can be the scheduler when the user opts in (schedule.auto_tick):
@@ -158,10 +158,13 @@ module Samagotchi
158
158
  # Worker#leave_scratch, or any other way out), now the lock is free.
159
159
  # Its terminal may have deleted it first.
160
160
  private def delete_left_scratch(session_id, state_dir:)
161
- SessionManager.delete_session(session_id, state_dir: state_dir)
161
+ policy = SessionManager::RunningTasks::Policy.stop(by: "scratch")
162
+ SessionManager.delete_session(session_id, state_dir: state_dir, running_tasks: policy)
162
163
  Log.info(:worker, "scratch_deleted", sid: session_id)
163
164
  rescue SessionManager::DeleteRefused, ArgumentError, SystemCallError => e
164
165
  Log.info(:worker, "scratch_kept", sid: session_id, error: e.class.name, msg: e.message)
166
+ ensure
167
+ SessionManager::RunningTasks.log_automatic!(policy) if policy
165
168
  end
166
169
 
167
170
  # Delete a session its worker left empty. Checked again now the lock is
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: samagotchi
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.178.0
4
+ version: 0.179.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Dmitry Dedov
@@ -200,6 +200,7 @@ files:
200
200
  - lib/samagotchi/bridge/bounded_queue.rb
201
201
  - lib/samagotchi/bridge/card_places.rb
202
202
  - lib/samagotchi/bridge/card_store.rb
203
+ - lib/samagotchi/bridge/card_wait.rb
203
204
  - lib/samagotchi/bridge/client_event.rb
204
205
  - lib/samagotchi/bridge/event_id.rb
205
206
  - lib/samagotchi/bridge/pending_card.rb
@@ -234,6 +235,7 @@ files:
234
235
  - lib/samagotchi/bundle_command/try/run.rb
235
236
  - lib/samagotchi/bundle_command/try/sandbox.rb
236
237
  - lib/samagotchi/bundle_command/try/trace.rb
238
+ - lib/samagotchi/bundle_manifest.rb
237
239
  - lib/samagotchi/bundle_needs.rb
238
240
  - lib/samagotchi/bundle_settings_check.rb
239
241
  - lib/samagotchi/bundler_env.rb
@@ -460,6 +462,16 @@ files:
460
462
  - lib/samagotchi/idle_target.rb
461
463
  - lib/samagotchi/image_store.rb
462
464
  - lib/samagotchi/inline_widgets.rb
465
+ - lib/samagotchi/installed_bundles.rb
466
+ - lib/samagotchi/installed_bundles/bundle_hook.rb
467
+ - lib/samagotchi/installed_bundles/dir.rb
468
+ - lib/samagotchi/installed_bundles/file_digest.rb
469
+ - lib/samagotchi/installed_bundles/file_standing.rb
470
+ - lib/samagotchi/installed_bundles/manifest.rb
471
+ - lib/samagotchi/installed_bundles/plugin_ref.rb
472
+ - lib/samagotchi/installed_bundles/record.rb
473
+ - lib/samagotchi/installed_bundles/sha.rb
474
+ - lib/samagotchi/installed_bundles/standing.rb
463
475
  - lib/samagotchi/installed_gem.rb
464
476
  - lib/samagotchi/installed_versions.rb
465
477
  - lib/samagotchi/interrupted_turn.rb
@@ -512,26 +524,15 @@ files:
512
524
  - lib/samagotchi/memory_bundle/asset_installer.rb
513
525
  - lib/samagotchi/memory_bundle/asset_state.rb
514
526
  - lib/samagotchi/memory_bundle/builder.rb
515
- - lib/samagotchi/memory_bundle/bundle_hook.rb
516
- - lib/samagotchi/memory_bundle/entry_size.rb
517
527
  - lib/samagotchi/memory_bundle/file_actions.rb
518
- - lib/samagotchi/memory_bundle/file_digest.rb
519
- - lib/samagotchi/memory_bundle/file_standing.rb
520
528
  - lib/samagotchi/memory_bundle/file_state.rb
521
- - lib/samagotchi/memory_bundle/index_size.rb
522
- - lib/samagotchi/memory_bundle/index_sync.rb
523
- - lib/samagotchi/memory_bundle/index_updater.rb
524
- - lib/samagotchi/memory_bundle/installed_bundle.rb
525
529
  - lib/samagotchi/memory_bundle/installed_copy.rb
526
- - lib/samagotchi/memory_bundle/installed_manifest.rb
527
530
  - lib/samagotchi/memory_bundle/installer.rb
528
531
  - lib/samagotchi/memory_bundle/listing.rb
529
- - lib/samagotchi/memory_bundle/manifest.rb
530
532
  - lib/samagotchi/memory_bundle/manifest_standing.rb
531
533
  - lib/samagotchi/memory_bundle/memory_files.rb
532
534
  - lib/samagotchi/memory_bundle/merger.rb
533
535
  - lib/samagotchi/memory_bundle/placeholder.rb
534
- - lib/samagotchi/memory_bundle/plugin_ref.rb
535
536
  - lib/samagotchi/memory_bundle/profile.rb
536
537
  - lib/samagotchi/memory_bundle/provenance.rb
537
538
  - lib/samagotchi/memory_bundle/remerge.rb
@@ -545,6 +546,10 @@ files:
545
546
  - lib/samagotchi/memory_bundle/trash.rb
546
547
  - lib/samagotchi/memory_bundle/uninstaller.rb
547
548
  - lib/samagotchi/memory_command.rb
549
+ - lib/samagotchi/memory_index/entry_size.rb
550
+ - lib/samagotchi/memory_index/size.rb
551
+ - lib/samagotchi/memory_index/sync.rb
552
+ - lib/samagotchi/memory_index/updater.rb
548
553
  - lib/samagotchi/memory_orphans.rb
549
554
  - lib/samagotchi/memory_paths.rb
550
555
  - lib/samagotchi/memory_usage.rb
@@ -590,6 +595,7 @@ files:
590
595
  - lib/samagotchi/participants.rb
591
596
  - lib/samagotchi/participants_watch.rb
592
597
  - lib/samagotchi/paths.rb
598
+ - lib/samagotchi/peer_exchanges.rb
593
599
  - lib/samagotchi/peer_sources.rb
594
600
  - lib/samagotchi/pending_question.rb
595
601
  - lib/samagotchi/plugin/api.rb
@@ -1124,6 +1130,7 @@ files:
1124
1130
  - lib/samagotchi/web/public/turn_model.js
1125
1131
  - lib/samagotchi/web/public/turn_pieces.js
1126
1132
  - lib/samagotchi/web/public/turn_range.js
1133
+ - lib/samagotchi/web/public/turn_settle.js
1127
1134
  - lib/samagotchi/web/public/unqueue.js
1128
1135
  - lib/samagotchi/web/public/update_notice.js
1129
1136
  - lib/samagotchi/web/public/update_sheet.js