samagotchi 0.201.0 → 0.202.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 (175) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +57 -1
  3. data/docs/architecture.md +47 -7
  4. data/docs/cli.md +20 -1
  5. data/docs/configuration.md +2 -1
  6. data/docs/internals/bridge.md +4 -4
  7. data/docs/internals/engine.md +9 -6
  8. data/docs/internals/knowledge.md +26 -6
  9. data/docs/internals/objectives.md +2 -2
  10. data/docs/internals/pages.md +4 -2
  11. data/docs/internals/participants.md +1 -1
  12. data/docs/internals/peers.md +9 -7
  13. data/docs/internals/remote-sessions.md +6 -6
  14. data/docs/internals/session-lifecycle.md +37 -15
  15. data/docs/internals/web-frontend.md +18 -7
  16. data/docs/pages.md +6 -3
  17. data/docs/plugins.md +2 -2
  18. data/docs/scheduling.md +40 -12
  19. data/docs/sessions.md +48 -6
  20. data/docs/sub-agent.md +1 -2
  21. data/docs/testing.md +92 -8
  22. data/lib/samagotchi/answer_display.rb +3 -2
  23. data/lib/samagotchi/answer_tail.rb +4 -4
  24. data/lib/samagotchi/bridge/card_places.rb +5 -5
  25. data/lib/samagotchi/bridge/turn_accumulator.rb +5 -5
  26. data/lib/samagotchi/bridge/turn_drawings/synth.rb +5 -5
  27. data/lib/samagotchi/bridge/turn_drawings.rb +2 -2
  28. data/lib/samagotchi/bridge/turn_ranges.rb +15 -8
  29. data/lib/samagotchi/bridge.rb +5 -5
  30. data/lib/samagotchi/broadcast_command.rb +3 -3
  31. data/lib/samagotchi/bundle_command/try/trace.rb +18 -6
  32. data/lib/samagotchi/bundles/knowledge/embedder.rb +2 -0
  33. data/lib/samagotchi/bundles/knowledge/github.rb +19 -0
  34. data/lib/samagotchi/bundles/knowledge/manifest.yml +6 -6
  35. data/lib/samagotchi/bundles/knowledge/plugin.rb +26 -54
  36. data/lib/samagotchi/bundles/knowledge/refresh.rb +89 -14
  37. data/lib/samagotchi/bundles/knowledge/store.rb +36 -2
  38. data/lib/samagotchi/bundles/schedules/manifest.yml +2 -2
  39. data/lib/samagotchi/bundles/schedules/scripts/schedules.rb +24 -3
  40. data/lib/samagotchi/bundles/system/config_modification_protocol.md +1 -1
  41. data/lib/samagotchi/bundles/system/manifest.yml +3 -3
  42. data/lib/samagotchi/bundles/system/skill_pages.md +1 -1
  43. data/lib/samagotchi/chi_invocation.rb +1 -1
  44. data/lib/samagotchi/child_move.rb +6 -3
  45. data/lib/samagotchi/child_reports.rb +3 -3
  46. data/lib/samagotchi/children_status.rb +4 -2
  47. data/lib/samagotchi/client_id.rb +2 -2
  48. data/lib/samagotchi/compat.rb +4 -6
  49. data/lib/samagotchi/config.rb +3 -0
  50. data/lib/samagotchi/context_note.rb +1 -1
  51. data/lib/samagotchi/continue_intent.rb +1 -1
  52. data/lib/samagotchi/continue_offer.rb +2 -2
  53. data/lib/samagotchi/continue_repair_backoff.rb +71 -0
  54. data/lib/samagotchi/delivery.rb +1 -4
  55. data/lib/samagotchi/engine/participants.rb +1 -1
  56. data/lib/samagotchi/engine/recap.rb +1 -1
  57. data/lib/samagotchi/engine/turn_end.rb +1 -1
  58. data/lib/samagotchi/grants.rb +2 -2
  59. data/lib/samagotchi/guardrail_wiring.rb +1 -1
  60. data/lib/samagotchi/guardrails/approval.rb +3 -3
  61. data/lib/samagotchi/guardrails/pair_boundary.rb +3 -3
  62. data/lib/samagotchi/guardrails/participant_refusal.rb +2 -2
  63. data/lib/samagotchi/idle_recap.rb +6 -6
  64. data/lib/samagotchi/kernel_loop.rb +1 -1
  65. data/lib/samagotchi/last_turn.rb +9 -6
  66. data/lib/samagotchi/llm/chat_loop.rb +5 -2
  67. data/lib/samagotchi/mcp_command.rb +2 -2
  68. data/lib/samagotchi/memory_usage.rb +7 -6
  69. data/lib/samagotchi/note_command.rb +1 -1
  70. data/lib/samagotchi/note_delivery.rb +5 -5
  71. data/lib/samagotchi/objectives_backing.rb +3 -3
  72. data/lib/samagotchi/objectives_record.rb +2 -2
  73. data/lib/samagotchi/objectives_track.rb +2 -2
  74. data/lib/samagotchi/owner_lock.rb +28 -2
  75. data/lib/samagotchi/owner_prompt.rb +3 -3
  76. data/lib/samagotchi/pages/runtime.rb +9 -4
  77. data/lib/samagotchi/participant_revise.rb +6 -6
  78. data/lib/samagotchi/peer_receipts.rb +11 -4
  79. data/lib/samagotchi/plugin/side_question.rb +1 -1
  80. data/lib/samagotchi/recap_place.rb +5 -5
  81. data/lib/samagotchi/reply_for.rb +3 -3
  82. data/lib/samagotchi/reply_wait/liveness.rb +2 -2
  83. data/lib/samagotchi/reply_wait/poll.rb +3 -3
  84. data/lib/samagotchi/schedule_command.rb +1 -1
  85. data/lib/samagotchi/schedule_display.rb +4 -3
  86. data/lib/samagotchi/schedules/busy_part.rb +29 -5
  87. data/lib/samagotchi/schedules/history_part.rb +47 -7
  88. data/lib/samagotchi/schedules/marks_part.rb +52 -29
  89. data/lib/samagotchi/schedules/notices_part.rb +31 -4
  90. data/lib/samagotchi/schedules/protection_part.rb +69 -11
  91. data/lib/samagotchi/schedules/prune_part.rb +3 -2
  92. data/lib/samagotchi/schedules.rb +37 -47
  93. data/lib/samagotchi/send_command.rb +12 -12
  94. data/lib/samagotchi/session.rb +71 -59
  95. data/lib/samagotchi/session_access/contract.rb +7 -0
  96. data/lib/samagotchi/session_access/exchange.rb +1 -1
  97. data/lib/samagotchi/session_access/local.rb +9 -9
  98. data/lib/samagotchi/session_access/remote.rb +20 -24
  99. data/lib/samagotchi/session_access.rb +1 -1
  100. data/lib/samagotchi/session_chain/delete.rb +15 -8
  101. data/lib/samagotchi/session_chain/delete_preview.rb +3 -3
  102. data/lib/samagotchi/session_chain/links.rb +18 -4
  103. data/lib/samagotchi/session_chain/successor.rb +1 -1
  104. data/lib/samagotchi/session_chain.rb +3 -3
  105. data/lib/samagotchi/session_continue.rb +83 -32
  106. data/lib/samagotchi/session_inbox.rb +6 -17
  107. data/lib/samagotchi/session_inbox_delivery.rb +36 -13
  108. data/lib/samagotchi/session_lifecycle/allowed.rb +5 -5
  109. data/lib/samagotchi/session_manager/delegate_rule.rb +2 -2
  110. data/lib/samagotchi/session_manager/delivery.rb +13 -38
  111. data/lib/samagotchi/session_manager/emptiness.rb +35 -15
  112. data/lib/samagotchi/session_manager/lifecycle.rb +3 -2
  113. data/lib/samagotchi/session_manager/listing.rb +35 -10
  114. data/lib/samagotchi/session_manager/removal.rb +16 -0
  115. data/lib/samagotchi/session_manager/spawn.rb +9 -6
  116. data/lib/samagotchi/session_manager.rb +6 -4
  117. data/lib/samagotchi/session_messages.rb +602 -0
  118. data/lib/samagotchi/session_metrics.rb +7 -4
  119. data/lib/samagotchi/session_participants.rb +4 -4
  120. data/lib/samagotchi/session_protection.rb +16 -2
  121. data/lib/samagotchi/session_retention.rb +26 -12
  122. data/lib/samagotchi/session_row.rb +1 -1
  123. data/lib/samagotchi/session_stats.rb +17 -8
  124. data/lib/samagotchi/session_stores.rb +5 -0
  125. data/lib/samagotchi/session_transition.rb +3 -2
  126. data/lib/samagotchi/sessions_command.rb +55 -3
  127. data/lib/samagotchi/steer.rb +16 -50
  128. data/lib/samagotchi/storage_migration.rb +234 -0
  129. data/lib/samagotchi/terminal_ui/attached_loop.rb +3 -3
  130. data/lib/samagotchi/terminal_ui/formatting.rb +5 -5
  131. data/lib/samagotchi/terminal_ui/join_replay.rb +3 -3
  132. data/lib/samagotchi/terminal_ui/question_prompt.rb +2 -2
  133. data/lib/samagotchi/toolkit_report_command.rb +1 -1
  134. data/lib/samagotchi/tools/ask_session.rb +2 -2
  135. data/lib/samagotchi/tools/send_note.rb +1 -1
  136. data/lib/samagotchi/turn_context.rb +3 -3
  137. data/lib/samagotchi/turn_endings.rb +17 -0
  138. data/lib/samagotchi/turn_excerpts.rb +7 -4
  139. data/lib/samagotchi/turn_flow.rb +1 -1
  140. data/lib/samagotchi/turn_note.rb +30 -2
  141. data/lib/samagotchi/turn_origin.rb +7 -7
  142. data/lib/samagotchi/turn_outcome.rb +11 -0
  143. data/lib/samagotchi/turn_stages/verify_anchors.rb +4 -4
  144. data/lib/samagotchi/verify_fresh.rb +6 -6
  145. data/lib/samagotchi/verify_fresh_origin.rb +4 -4
  146. data/lib/samagotchi/version.rb +1 -1
  147. data/lib/samagotchi/web/app.rb +4 -3
  148. data/lib/samagotchi/web/last_ask.rb +2 -2
  149. data/lib/samagotchi/web/message_display.rb +12 -12
  150. data/lib/samagotchi/web/page_routes.rb +9 -3
  151. data/lib/samagotchi/web/participant_view.rb +4 -4
  152. data/lib/samagotchi/web/participants_admin.rb +1 -1
  153. data/lib/samagotchi/web/public/bubbles.js +1 -1
  154. data/lib/samagotchi/web/public/composer_fold.js +0 -3
  155. data/lib/samagotchi/web/public/composer_grip.js +0 -2
  156. data/lib/samagotchi/web/public/page_view.js +29 -4
  157. data/lib/samagotchi/web/public/participant_model.js +1 -1
  158. data/lib/samagotchi/web/public/peer_wait.js +2 -4
  159. data/lib/samagotchi/web/public/schedule_marks.js +2 -5
  160. data/lib/samagotchi/web/public/schedule_name.js +14 -0
  161. data/lib/samagotchi/web/public/session_actions.js +5 -0
  162. data/lib/samagotchi/web/public/start_page.js +1 -1
  163. data/lib/samagotchi/web/public/stop_sheet.js +2 -4
  164. data/lib/samagotchi/web/public/working_set_rail.js +0 -3
  165. data/lib/samagotchi/web/push/attention.rb +1 -1
  166. data/lib/samagotchi/web/session_create.rb +1 -1
  167. data/lib/samagotchi/web/session_hub.rb +68 -20
  168. data/lib/samagotchi/web/session_summary.rb +18 -14
  169. data/lib/samagotchi/web/verify_fresh_routes.rb +4 -4
  170. data/lib/samagotchi/worker/turn_drain.rb +158 -0
  171. data/lib/samagotchi/worker.rb +8 -144
  172. data/lib/samagotchi/worker_boot.rb +21 -5
  173. data/lib/samagotchi/worker_participant_gate.rb +5 -5
  174. data/lib/samagotchi/worker_presence.rb +24 -1
  175. metadata +6 -1
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 6043b2afd5373b6f0c2f2e136ec49fa1ec6ef1053b6180733af7853b3c5139e7
4
- data.tar.gz: cd53ab7b2325b54baa15ce6d1d90f016c04f70638d655d89728157624b6fb91f
3
+ metadata.gz: fe1c4e56f488403c84fcb7bfd5ddd11a0e6c045e8d300b9bd4e95c47ba521734
4
+ data.tar.gz: 0c5aabc03f6a07f222f49d6c521028485147b13ab055d8e09ad9b05887ad7822
5
5
  SHA512:
6
- metadata.gz: fe5a9713e30c8e7b010f21a600aca1c93b396e9cc2866247eab439613728489f3ef04ce7f196bea339b9de7df8d430ec86dbf72236ad9ec44307bbcd0b84786d
7
- data.tar.gz: bd87868ca9dd23766a1dec24a693eb8cdb41c072b5b8a93f52e9a7f4d847c6c021d6e1fd307a488f781b9de6b89b4c4bfcbd0f885912acf1cb79c148708bbbdd
6
+ metadata.gz: 810f577bab091ea1f011e9b04687375e76b610dc5316e4183978a9f083de6a145c41b198972d54ef85701c3ef627d4dab02fac1afe773c05bfa18299cf577358
7
+ data.tar.gz: d8a851e52eda1204aee6028a7fbd8d543bdd248d46ba36351da9c3db5f79fccfc0dd31bc54153181bfdf67798fee8184b7ee322ff51466060611bc47fe2b9431
data/CHANGELOG.md CHANGED
@@ -8,6 +8,61 @@ and commands may change between minor versions. How releases are made:
8
8
 
9
9
  ## [Unreleased]
10
10
 
11
+ ## [0.202.0] - 2026-12-05
12
+
13
+ ### Added
14
+
15
+ - The debug log (and `chi -v`) has one `save_shape` line per session save, saying how the conversation changed since
16
+ the last save (`append`, `head`, `rewrite at=k`…): it measures how sessions are saved, ahead of a lighter session file.
17
+ - `session.split_messages` (off by default): a session's conversation is kept in its own file beside `<id>.json`, so
18
+ saving a turn appends instead of rewriting the whole session, and listings read only the small session file. chi
19
+ 0.201.0 and older show such a session as empty (nothing is lost). `chi sessions migrate` converts saved sessions
20
+ (`--dry-run` reports).
21
+
22
+ ### Changed
23
+
24
+ - chi no longer falls back to `cli:send` for an agent's turn sent to a worker or chi web older than 0.185.0.
25
+ - chi web works out which session each schedule waits on (the line under the session bar, the card's schedule badge)
26
+ from the sessions it already holds instead of reading every session file again: on a fleet of ~400 sessions, about
27
+ 200 ms and ~900k allocations every 5 s while a session saves become about 2 ms.
28
+
29
+ ### Fixed
30
+
31
+ - A session waiting on its delegates (and the delegate tools) no longer builds a summary row for every session each
32
+ poll, only for its own children: about a third less time per check on a fleet of ~400 sessions.
33
+ - The retention sweep (and `chi sessions prune`) now removes a session folder left with only an `analytics.json` after
34
+ its session file went, once it is older than `session.retention_days`; before, such folders stayed forever.
35
+ - chi web no longer lists every session each second while a continue runs.
36
+ - Listing sessions (`chi sessions list` and the other readers of the session list) no longer reads the archived
37
+ sessions it leaves out: on a fleet with many archived sessions, it takes about half the time.
38
+ - A crashed continue whose repair keeps failing on the disk (full, or not writable) no longer stops the session lists
39
+ updating: it is logged once and tried again after a minute, then less often.
40
+ - chi web: a page run whose tapped choice the script no longer has no longer takes the default silently: a toast
41
+ says what ran instead (`Ran Period: 7 days: 90 days is no longer a choice`).
42
+ - chi web: the Stop sheet (or the Stop confirm) no longer opens over another session when the open one changes while
43
+ the worker's holds are being read; the next Stop asks again.
44
+ - knowledge: a worker on an older chi no longer drops and rebuilds the index a newer chi made (the two sharing a
45
+ catalog, as after an upgrade with sessions still running): it leaves it as it is and its source's age line says why.
46
+ - knowledge: removing a source, or adding it again (a named catalog's sessions source from another project, other
47
+ globs), while a refresh of it runs no longer lets that refresh put its rows back, record its time on the new source,
48
+ or leave a removed GitHub source's clone on disk.
49
+ - knowledge: a deleted session's text leaves the index at the next search or `knowledge_add` of its catalog, not only at
50
+ a search that selects the sessions source.
51
+ - chi web: the line under the session bar names a schedule a stopped session holds in two cases it missed: while a
52
+ one-turn run (`chi -p X --non-interactive`) holds the stopped session, and when you stop a session while a
53
+ schedule's firing on it is in flight (the Stop sheet named that schedule, the bar didn't).
54
+ - A schedule whose turn fails because the host doesn't serve the session's model, or refused the key, turns itself off
55
+ at that first failure (it used to try 3 times) and says how to fix it: `host main doesn't serve main:m: /model
56
+ main:served or edit the session's model`, in the phone notification, `chi schedule show` and the Schedules page
57
+ ("off: needs a fix"). A flaky failure (a connection, a server error, a timeout) still gets 3 tries. Update the
58
+ schedules bundle with `chi update` (0.1.2) for its new line.
59
+ - Continuing, archiving, deleting or moving a session with delegates lists the sessions once instead of once per
60
+ delegate (a continue of a session with 10 sessions under it read every session file 34 times in its first check).
61
+ - chi web: archiving or unarchiving a session now moves a schedule's line under the session bar (and its badge) to the
62
+ chain's new end within seconds; before, it waited for another session to save or for `schedules.json` to change.
63
+
64
+ Update with `chi update` (knowledge 0.3.2, schedules 0.1.2).
65
+
11
66
  ## [0.201.0] - 2026-12-05
12
67
 
13
68
  ### Added
@@ -7358,7 +7413,8 @@ and long-lived sessions.
7358
7413
  - A macOS desktop helper (`chi desktop install`): a "Send to chi" Service and a
7359
7414
  hotkey panel that send selected text or the clipboard to your sessions.
7360
7415
 
7361
- [Unreleased]: https://github.com/dm1try/samagotchi/compare/v0.201.0...HEAD
7416
+ [Unreleased]: https://github.com/dm1try/samagotchi/compare/v0.202.0...HEAD
7417
+ [0.202.0]: https://github.com/dm1try/samagotchi/compare/v0.201.0...v0.202.0
7362
7418
  [0.201.0]: https://github.com/dm1try/samagotchi/compare/v0.200.0...v0.201.0
7363
7419
  [0.200.0]: https://github.com/dm1try/samagotchi/compare/v0.199.0...v0.200.0
7364
7420
  [0.199.0]: https://github.com/dm1try/samagotchi/compare/v0.198.0...v0.199.0
data/docs/architecture.md CHANGED
@@ -223,6 +223,46 @@ require, and so does every caller of its class methods; `SessionCommands` (the r
223
223
  `Tools::Execute`) only includes it, for its constants. A new client-side read of either goes to the table or the
224
224
  catalogue, never to the class.
225
225
 
226
+ ## Codes beside words
227
+
228
+ Anything chi stores (a file, a history row, a session field) or sends across a process (a Bridge or chi web
229
+ answer, an event, a remote's reply) carries a machine **code** beside its **words**. The words are for display;
230
+ no reader matches them to decide anything, except as the fallback for data an older chi wrote without the code
231
+ (keep that fallback: compat N-1). Rewording a sentence then never reclassifies a stored row or a remote's answer.
232
+ The house examples: an exception's `reason` symbol (`SessionContinue::Refused#reason`, `ArchiveRefused#reason`); a
233
+ wire refusal's `{error: <code>, detail: <words>}` (`DeliverResult::STOPPED`); a turn's stop facts (`LastTurn`'s
234
+ `error_kind`, `cancel_reason`, `stopped_by`); a schedule history row's `code` beside its `detail`
235
+ ([Scheduling](scheduling.md)). Code→words tables sit at the edge that shows them (`ASK_BUSY_WORDS`,
236
+ `question_card.js`). Model-facing text is never reworded for this (the prompt cache): a key goes beside it. Where a
237
+ reader can only see words (tool-output prefixes in old messages, which `ToolActivity` and chi web's read view
238
+ match), a sync spec pins the words to the Ruby that writes them (`spec/tool_output_prefix_sync_spec.rb`; also
239
+ `spec/pages_name_sync_spec.rb`).
240
+
241
+ ## Facts and operations
242
+
243
+ The session modules come in two kinds. **Facts** read files and answer: the session files and the listing, the
244
+ inbox's file queue (`SessionInbox`), the owner lock (`OwnerLock.for_session`), the chain walkers
245
+ (`SessionChain::Links`, `Successor`, `Sharing`), the schedules file and its questions (`anchor_heads`, the
246
+ protection holds). **Operations** change the fleet: spawn, deliver (`InboxDelivery`), stop, archive, delete,
247
+ continue, a schedule's tick and firing. The rule: **a fact never calls an operation; an operation may call facts.**
248
+ So the many readers of a fact (the Worker, the Bridge, ReplyWait, chi web) don't load or depend on everything the
249
+ operations reach, and a new reader can't start a worker by accident.
250
+
251
+ It is not true yet. Today's known exceptions, all inside one class cycle:
252
+ - The listing (`SessionManager.session_rows` / `children_of` / `descendant_ids`) lives on the manager and runs
253
+ `SessionContinue.repair_interrupted` first, so every listing reader (`ChildrenStatus`, `DelegateRule`,
254
+ `ChildMove`) reaches continue through it.
255
+ - `Schedules` is one class for the file's facts and the tick: the chain walker (`Links#anchor_heads`) and the
256
+ protection check (`SessionProtection`) build a whole `Schedules` behind a deferred `require`.
257
+ - Chain delete and the manager's removal call each other (`delete_session` takes `SessionChain::Delete`, which
258
+ calls back into the removal), and `SessionRetention` deletes through the manager.
259
+
260
+ `spec/architecture/class_cycle_spec.rb` pins it: the largest strongly connected component of the class reference
261
+ graph (Prism scan, an edge from each reference's lexical scope to the constant it names) stays at or below its pin
262
+ (the spec's `pin`: the size measured, with the date). A failure lists the component: a new two-way reference joined
263
+ it. Remove the reference (pass the fact in, move it below the operation) rather than raise the pin; when a change
264
+ shrinks the cycle, lower it.
265
+
226
266
  ## Session retention & ordering
227
267
 
228
268
  - **Files:** `~/.local/state/samagotchi/sessions/<uuid>.json` + `<uuid>/input|output|owner.lock|bridge.json` (XDG-aware), and the `<uuid>/stopped`, `<uuid>/starting` and `<uuid>/archived` marker files. Durable schedules belong to the machine, not a session: `~/.local/state/samagotchi/schedules.json` and its `schedules.lock`, next to `sessions/` ([Scheduling](scheduling.md)).
@@ -231,7 +271,7 @@ catalogue, never to the class.
231
271
  - **Starting:** every spawn marks the session starting (`<uuid>/starting`, `{pid, at}`, `StartingMarker`) until its worker holds the lock: `spawn_worker_for_session` writes it with its own pid before `Process.spawn` and the starter's after (the starter lives until the worker holds the lock, at most `WORKER_START_GRACE`; a spawn that raises or whose starter is gone leaves none), `spawn_session` before the new file is saved, and `Worker#start` removes it. It holds for 60 s at most, and only while the pid it names runs. A resume claims it (`StartingMarker.claim`, a link(2): of resumes racing from any processes one wins), then reads the owner again. A stop marker cancels the hold-off (`start_pending?` = starting and not stop-marked) for a start marked before the stop only: of two sends after a stop, the claim lets one spawn. The stop marker carries its own `at` (`{"at"}`, on the starting marker's clock; `Session.stopped_at`), an older chi's empty one its mtime. The sweep, archive (`:starting`) and delete (refused as an owned session) honour it. N-1: an older spawner writes none for a resume (the owner checks stay); an older worker never leaves one it was given (every worker clears it at start); a leftover one is stale by age or pid (a claim's temp files a kill left, `starting.*`, count as skeleton); a 0.160 spawner or chi web still holds off on a fresh marker under a stop (it reads `starting?` before the stop), until the start ends or 60 s. `SessionManager` keeps only its starters' pids, for chi web's restart to adopt (`live_spawn_pids`), and decides nothing from them.
232
272
  - **Deleting:** `delete_session`, the retention sweep and a failed continue's cleanup use `remove_files` for the session JSON, sidecar dir, plugin state, attached context, participant grants, System 1 runs and context-candidate records. `SessionStores` registers the sidecar filenames and the removal categories (what a delete removes), `SessionProtection` its protectors (what refuses one: an enabled schedule's anchor, head and target; fail-closed); `remove_session_files` deletes the whole sidecar directory, so those files need no individual removal path. The JSON and dir go through `remove_session_files`, holding the owner lock (kind `deleting`, which `stop_session` never signals; not waited for: a worker that took it since the check keeps the session) and reading the starting marker again under it (a resume that claimed the start just before keeps the session; one after it sees the lock held). N-1: an older chi's stop reading the owner then would TERM the deleter (chi web, the CLI) in that moment; an older reader shows the kind as unknown. `Session#save` of a session read from its file (or saved once) skips a file that is gone (log `save_skipped_deleted`) rather than recreate it; only a new session's first save creates one.
233
273
  - **Worker presence:** whether a worker is up, coming or held off is read once per decision as a `WorkerPresence` (`worker_presence.rb`, a `Data.define`), the deciders' one reader of those facts (display and list rows still read `session_owner` / `WorkerLink` themselves): the owner lock's holder, the stop marker (`stop_marked?`: the only "stopped" a decider reads, never the session file's status), the `starting` marker (`StartingMarker`, `starting?`, `start_pending?`: every spawn writes it, see Starting), the archive marker, the session file's existence, and the `WorkerLink` outcome when asked (never the file itself: a scratch session's flag is read by `WakePolicy`, last). The deciders read it: `resume_session` (tui, owned, `resume_held_off?`), the session inbox's `WakePolicy` (a ring, a push's wake, a note, a fresh verdict, `wake_for_report`, `deliver_turn`'s two liveness checks, `WorkerBoot`'s leave: below), `Local#wake`/`#worker`, `AttachLauncher`, `Schedules#busy_reason` (its state's answer through `SessionLifecycle`: `Reading.derive` and `ALLOWED`), archive, delete and the retention sweep. Each keeps its own subset of the facts and their order.
234
- - **Session inbox:** a delivery into a session (`SessionInbox.deliver(kind, id) { |at| write }`, `session_inbox_delivery.rb`) runs one path: resolve the link (`SessionInbox::Head.resolve`: push and a fresh verdict are pinned to the id named; a send and a note go to the chain's newest link, and for a send (a kind that starts an archived link) a continue of the reached link in flight (`ContinueIntent.in_flight`: `continue.json` written, `continue.lock` held, the successor not saved yet) gives `:continuing` with the successor's id, which chi send asks again for a moment and then refuses; a note needs no such check (`NoteMove` moves or adopts it); a ring's file stays with the parent `parent.json` names and its wake goes one hop, to the link whose `ChildReports` reads that file; only an archived id is walked, with one `Session.list`: `SessionChain::Links#first_live`), refuse before any write (a gone session; a one-turn run's or a scratch session for send and a note), write with the kind's own writer (formats unchanged), read `WorkerPresence` once, and apply the kind's `WakePolicy` row. `decide` reads in one order for every kind: gone, one-turn run (`:owned`), owned (`:live`), the stop marker (`:stopped`: the only "stopped", the file's status never decides; send un-stops), archived (send alone starts one), starting (`:starting`, never a second spawn), the kind never starts (`:none`: a note, a fresh verdict) or wasn't asked to (`:off`), scratch (the session file is read only here), else `:start` through `SessionManager.start_for_inbox` (`resume_session`, its claim on the starting marker; it answers `:woken` only when it spawned the worker, `:starting` when another start won the claim, `:live` when a worker took the lock since). N-1 gap: a session file that says `stopped` with no stop marker (stopped before the marker existed, or a resume whose spawn failed after it cleared the marker) is woken, and an older worker, which has no `Worker#settle_stale_status`, exits on its first pass; the wake still reads `:woken`, and each later ring or push spawns another such worker (bounded by the rings and pushes). Restarting chi on the new version (`chi web`, the workers) closes it. `SessionInbox.wake` is the wake half alone (`wake_for_report`, a failed continue's rings). On it: `ChildRing.ring` (its start on a thread), `Local#context_push`'s wake (its outcome is `ContextPush#wake`, the push line's ending), `NoteDelivery.deliver` (every note writer a person or another session drives: `chi note`, `send_note`, `chi broadcast`, chi web's notes route; `NoteDelivery::Result#id` is the link that has it, `#asked` the one named; `/objectives` passes `pin: true`: its list is its own session's) and `VerifyFresh.forward` (`:fresh_verdict`: the child's parent, pinned, no worker). Send keeps its Bridge/file flow in `SessionManager.deliver_turn`, which resolves nothing (it acts on the id it is given: an archived link gets the message and comes back); chi send resolves the head first (`SessionAccess#head`, remotely `GET /api/sessions/resolve?head=1`), while the web composer, a participant's turn, `delegate` follow-ups, `Plugin::Sessions` and `Schedules` stay on the id they name; its two liveness checks (before the post, after a file's write) read the sender's row (`WakePolicy.for_sender(client_id)`, `ClientId.wake_kind`: a person's — chi send, a web tab, a TUI — is `:send`; a schedule, a plugin, a delegate follow-up and a participant have rows of their own, any other id `:automatic`, which start an idle session but neither un-stop nor start an archived link: refused before the write, `DeliverResult::STOPPED` / `ARCHIVED`) and leave the other refusals to `resume_session`'s wording. One row is not a delivery: `:leave`, `WorkerBoot.run_session_loop`'s successor as a worker leaves (input left after a signal, an idle exit's or `/exit`'s input or rings, a restart), read on a fresh presence once the lock is free: a stop that landed as it left starts none for any way out (`resume_session` would clear the stop; logged `respawn_dropped`, `restart_dropped` for a restart, whose reminders go with it), the input and rings stay for the next start. The notes a spawn writes into the session it starts stay direct `SessionInbox.write_note` calls, pinned by construction: spawn_session's chain note, `ContextMove`'s notes, `Objectives.carry`, `ChildMove`'s note to a moved child. A continue moves the previous link's waiting notes to the new link last in its `before_spawn` (`NoteMove.move`), a failed one gives them back before the link goes (`NoteMove.give_back`), and the new link's worker adopts what the archived links before it get after their continue (`NoteMove.adoption`, from `WorkerInbound#absorb_notes` and `Worker#start`: back along the chain through up to 8 archived links, from each only notes from the creation of the link that continued it, never an objectives list). `write_note` refuses a session with no file and no folder (`Session::NotFound`), so a late writer can't bring back a deleted link's folder.
274
+ - **Session inbox:** a delivery into a session (`InboxDelivery.deliver(kind, id) { |at| write }`, `session_inbox_delivery.rb`) runs one path: resolve the link (`InboxDelivery::Head.resolve`: push and a fresh verdict are pinned to the id named; a send and a note go to the chain's newest link, and for a send (a kind that starts an archived link) a continue of the reached link in flight (`ContinueIntent.in_flight`: `continue.json` written, `continue.lock` held, the successor not saved yet) gives `:continuing` with the successor's id, which chi send asks again for a moment and then refuses; a note needs no such check (`NoteMove` moves or adopts it); a ring's file stays with the parent `parent.json` names and its wake goes one hop, to the link whose `ChildReports` reads that file; only an archived id is walked, with one `Session.list`: `SessionChain::Links#first_live`), refuse before any write (a gone session; a one-turn run's or a scratch session for send and a note), write with the kind's own writer (formats unchanged), read `WorkerPresence` once, and apply the kind's `WakePolicy` row. `decide` reads in one order for every kind: gone, one-turn run (`:owned`), owned (`:live`), the stop marker (`:stopped`: the only "stopped", the file's status never decides; send un-stops), archived (send alone starts one), starting (`:starting`, never a second spawn), the kind never starts (`:none`: a note, a fresh verdict) or wasn't asked to (`:off`), scratch (the session file is read only here), else `:start` through `SessionManager.start_for_inbox` (`resume_session`, its claim on the starting marker; it answers `:woken` only when it spawned the worker, `:starting` when another start won the claim, `:live` when a worker took the lock since). N-1 gap: a session file that says `stopped` with no stop marker (stopped before the marker existed, or a resume whose spawn failed after it cleared the marker) is woken, and an older worker, which has no `Worker#settle_stale_status`, exits on its first pass; the wake still reads `:woken`, and each later ring or push spawns another such worker (bounded by the rings and pushes). Restarting chi on the new version (`chi web`, the workers) closes it. `InboxDelivery.wake` is the wake half alone (`wake_for_report`, a failed continue's rings). On it: `ChildRing.ring` (its start on a thread), `Local#context_push`'s wake (its outcome is `ContextPush#wake`, the push line's ending), `NoteDelivery.deliver` (every note writer a person or another session drives: `chi note`, `send_note`, `chi broadcast`, chi web's notes route; `NoteDelivery::Result#id` is the link that has it, `#asked` the one named; `/objectives` passes `pin: true`: its list is its own session's) and `VerifyFresh.forward` (`:fresh_verdict`: the child's parent, pinned, no worker). Send keeps its Bridge/file flow in `SessionManager.deliver_turn`, which resolves nothing (it acts on the id it is given: an archived link gets the message and comes back); chi send resolves the head first (`SessionAccess#head`, remotely `GET /api/sessions/resolve?head=1`), while the web composer, a participant's turn, `delegate` follow-ups, `Plugin::Sessions` and `Schedules` stay on the id they name; its two liveness checks (before the post, after a file's write) read the sender's row (`WakePolicy.for_sender(client_id)`, `ClientId.wake_kind`: a person's — chi send, a web tab, a TUI — is `:send`; a schedule, a plugin, a delegate follow-up and a participant have rows of their own, any other id `:automatic`, which start an idle session but neither un-stop nor start an archived link: refused before the write, `DeliverResult::STOPPED` / `ARCHIVED`) and leave the other refusals to `resume_session`'s wording. One row is not a delivery: `:leave`, `WorkerBoot.run_session_loop`'s successor as a worker leaves (input left after a signal, an idle exit's or `/exit`'s input or rings, a restart), read on a fresh presence once the lock is free: a stop that landed as it left starts none for any way out (`resume_session` would clear the stop; logged `respawn_dropped`, `restart_dropped` for a restart, whose reminders go with it), the input and rings stay for the next start. The notes a spawn writes into the session it starts stay direct `SessionInbox.write_note` calls, pinned by construction: spawn_session's chain note, `ContextMove`'s notes, `Objectives.carry`, `ChildMove`'s note to a moved child. A continue moves the previous link's waiting notes to the new link last in its `before_spawn` (`NoteMove.move`), a failed one gives them back before the link goes (`NoteMove.give_back`), and the new link's worker adopts what the archived links before it get after their continue (`NoteMove.adoption`, from `WorkerInbound#absorb_notes` and `Worker#start`: back along the chain through up to 8 archived links, from each only notes from the creation of the link that continued it, never an objectives list). `write_note` refuses a session with no file and no folder (`Session::NotFound`), so a late writer can't bring back a deleted link's folder.
235
275
  - **Retention:** 14 days / 500 cap (env `SAMAGOTCHI_SESSION_RETENTION_DAYS`/`MAX_COUNT`, optional `KEEP_STATUS`), live-owner and starting guard (looked at again right before a session's files go), only when `*.json` present; lazy sweep at most once per `session.sweep_interval_hours` (default 24) from the session hub's full-probe tick (and on `GET /api/sessions`, which the page no longer calls), manual via `bin/chi sessions prune --dry-run`.
236
276
  - **Ordering:** `Session.list(sort:,order:,limit:,offset:)` and `GET /api/sessions?sort=&order=&limit=&offset=` default `updated_at desc`; Web UI sort/filter/pagination.
237
277
  - **Test hygiene:** `test_run` flag when `SAMAGOTCHI_ENV=test`/`RACK_ENV=test`/`CI`, targetable via `prune --test-only` / `clean`.
@@ -509,7 +549,7 @@ model: [internals/remote-sessions.md](internals/remote-sessions.md).
509
549
  | `POST /api/projects` | owner | `{dir}` (absolute folder; `~` and `~/` expand against the server's home) | 200 `{outcome, root, dir}` (`created`, `already_marked`, or `git`) | 400 `invalid_json`, `invalid_dir`; 422 `above_home`, `write_failed` |
510
550
  | `POST /api/sessions` (more fields) | owner | `toolkit`, `tools`, `no_tools`, `parent_answers`; `driver` (`agent:<name>`, the new session's driver); `client_id` (`cli:send`/`cli:answer`/`agent:<name>`: the first line is checked as chi send checks it); `check_vision: true` (images follow) | 201 adds `model_warning`, `parent_answers_warning` (a level looser than config.yml's, capped) and `first_turn_id` (the id the prompt it starts with gets for its turn; null for an `idle` create); with a `first_turn_id`, a wait `token` for that turn (none for an `idle` create) | 400 `invalid_toolkit`, `invalid_parent_answers`, `invalid_continues` (beside `continues`); 403 `parent_answers_refused`, `parent_continue_refused`; 422 `no_vision` |
511
551
  | `POST /api/sessions` (answered: any of `reply_for`, `timeout`, `request_id`) | owner | the ask's fields (`prompt`, `timeout`, `client_id`, `request_id`, `reply_for`) and the create's; `dir` optional: else `web.ask_dir` (`Config.get` per create, `StartDir.resolve(from: :ask_config)`), else the start folder. A `request_id` names the session (`SessionInbox.enqueued_id_for("create:" + key)`, `AskCreate::LOCKS` per id): a retry spawns nothing | 201: the ask's answer (as `POST …/ask`'s 200) + `session_id`, `created` (false: a retry's), `model_warning`, `parent_answers_warning`; the session spawns idle with the prompt as its preview, then `AskRoutes#run_ask`; records `last` (`Web::LastAsk`) unless a parent's line ([thin-clients.md](thin-clients.md#a-new-session-in-one-call)) | 400 `invalid_ask` (also beside `idle` or `continues`), `invalid_dir` (`web.ask_dir` not a folder), the ask's and the create's 400s, nothing spawned; after the spawn the ask's refusals keep their code and carry `session_id`, `created` |
512
- | `POST /api/sessions/:id/turn` (more fields) | owner | `client_id` as above; `check_vision: true` with `images` | as before | 403 `parent_answers_refused`, `parent_continue_refused`; 422 `no_vision`; 409 `link_continued` (`successor_id`) or `transition_busy` while a transition holds the session's lock (every sender: `SessionInbox::Hold`, internals/session-lifecycle.md) |
552
+ | `POST /api/sessions/:id/turn` (more fields) | owner | `client_id` as above; `check_vision: true` with `images` | as before | 403 `parent_answers_refused`, `parent_continue_refused`; 422 `no_vision`; 409 `link_continued` (`successor_id`) or `transition_busy` while a transition holds the session's lock (every sender: `InboxDelivery::Hold`, internals/session-lifecycle.md) |
513
553
  | `POST /api/sessions/:id/wait/prepare` | owner | `question_id` (absent: the pending one; `null`: none), `turn`, `created`, `busy` (+ `queue`) | 200 `{session_id, cursor, baseline: {messages, question_id, last_turn}, own_turn, known_turn, running, live, settled, last_turn_id}` (`WaitStart`) | 409 `busy`, `waiting` (`SendCommand::Busy`'s words, and its fields: `question`, `parent_strategy`) |
514
554
  | `POST /api/sessions/:id/wait` | owner | `cursor`, `baseline`, `turn`, `queued`, `ended_before`, `owner_grace`, `timeout` (capped at 30 s); or `{token, timeout}` (a wait token, `SessionAccess::Exchange::Token`: the answer adds `session_id`, and `token` again while the status is `timeout`; a token beside the other fields, another session's, one that isn't one or a participant's: 400 `invalid_wait`) | 200: `ReplyWait::Result`'s fields (`status`: `done`, `waiting_for_answer`, `no_reply`, `error`, `stopped`, `worker_gone`, or `timeout`: ask again; `text`, `file`, `question` as `PendingQuestion#to_file`, `outcome`, `limit`, `error_kind`, `retryable`, `cancel_reason`, `stopped_by`, `kept_steps`, `turn_id`, `origin`; never the session) and `parent_strategy` `{name, allowed, origin}` (`ParentReport.strategy_for`, this server's config.yml) | 400 `invalid_wait`; 503 `server_stopping` |
515
555
  | `POST /api/sessions/:id/ask` | owner | `:id` may be `last` (`Web::LastAsk.target`: the session the owner's last answered ask or answered create went to, kept in `last_ask.json` beside the sessions folder, following continues; gone or archived with no successor: the newest not scratch, delegate, `driver`, test run or archived; none: 404 `not_found`; a participant's: 404 at the gate; no `…/last/wait`); `prompt` (16 KiB), `timeout` (default and most 30 s), `queue` (default `true`: a running session queues it as its own turn; `false` refuses it), `client_id` (absent: `web:unnamed`; `cli:send`'s `/continue yes` goes in as `cli:answer` and is parent-gated as on `…/turn`), `request_id` (optional, 1-128 printable ASCII, messages only: a retry with it answers the first ask's turn, `SessionInbox.enqueued_id_for`) | 200: the wait's fields + `session_id` (where it ran), `asked` (the id given, when another link ran it), `token` when the status is `timeout`, `request_id` echoed when given; 200 `{status: command, session_id}` for a session command (`/continue yes` with an offer standing answers the continued turn's fields instead). The whole call answers within `AskRoutes::ASK_MAX_SECONDS` (35) (`Web::AskRoutes`, `SessionAccess::Ask`, [thin-clients.md](thin-clients.md)) | 404 `not_found`; 400 `ambiguous_id`, `missing_fields`, `invalid_prompt`, `local_command`, `invalid_ask` (also a `request_id` on a session command); 403 `parent_continue_refused`, `parent_answers_refused`; 409 `busy`, `waiting` (neutral words, Busy's fields), `continuing`, `owned_by_tui`, `enqueued_id_conflict` (the same `request_id`, another prompt, a turn the session no longer names but the worker remembers), the turn route's delivery refusals (`queue_unavailable`, …); 504 `worker_timeout`; 503 `server_stopping` |
@@ -556,8 +596,8 @@ verbatim) and the fields its class is built from, so a remote client raises the
556
596
  `owned_by_tui` (`session_id`), `worker_running`/`still_stopping`/`transition_held` (`DeleteRefused`: `session_id`, `reason`), `busy`/
557
597
  `scratch` (`ArchiveRefused`: `session_id`, `reason`, `busy_id`; reason `transition_held`'s `message` names the holder), a stop's
558
598
  `stop_held` (`SessionTransition::Busy`: `session_id`, `kind`, `successor_id`), a restart's `held`/`not_running`/`unsupported`/
559
- `failed` (`RestartRefused`: `session_id`, `reason`, `version`), a continue's `continued`/`open_children`/`folder_gone`/`transition_busy`
560
- (`SessionContinue::Refused`: `session_id`, `reason`, `ids`; `transition_busy`'s `message` names the holder) and `ambiguous_id` (`Session::AmbiguousId`: `ids`).
599
+ `failed` (`RestartRefused`: `session_id`, `reason`, `version`), a continue's `continued`/`open_children`/`folder_gone`/`transition_busy`/`undo_pending`
600
+ (`SessionContinue::Refused`: `session_id`, `reason`, `ids`; `transition_busy`'s `message` names the holder, `undo_pending`'s the error) and `ambiguous_id` (`Session::AmbiguousId`: `ids`).
561
601
  A session an id names none of is `404 not_found` with `Session::NotFound`'s words (`no session X`, `#session_not_found`):
562
602
  every lookup goes through `Session.resolve!` (an id or a unique prefix), and every surface shows that one message.
563
603
 
@@ -673,7 +713,7 @@ A map of the parts the overview above doesn't name (paths under `lib/samagotchi/
673
713
 
674
714
  | Component | Main file(s) | What it is |
675
715
  |---|---|---|
676
- | Worker | `worker.rb` (`worker_boot.rb`, `worker_idle_exit.rb`, `worker_inbound.rb`, `worker_signals.rb`, `worker_wakes.rb`, `worker_task_wakes.rb`, `task_watch.rb`, `worker_participant_gate.rb`, `worker_exit_claim.rb`) | A session's background process: builds the `Engine` and `Bridge`, runs queued turns and the wake turns nobody typed (delegate reports, a background task that finished unseen: [Finish wake](internals/background-tasks.md#finish-wake), attached context), exits when idle. A spawned one traps TERM, HUP and INT (`WorkerSignals`, installed by `WorkerBoot.run_session_loop` when `SAMAGOTCHI_WORKER_PROCESS=1`): the running turn stops as a Stop with reason `signal`, is saved, and the worker leaves (`:signal`, exit 0; a new worker only for input already queued). A running turn is checkpointed at its iteration boundaries (`TurnCheckpoint`, the `interrupted_turn` mark), and the next worker settles a turn its predecessor died in (`TurnCheckpoint.settle`). The session is saved from the turn's thread, Bridge threads and a signal's thread; `Session#save` takes a per-session lock around its snapshot and write, so an older snapshot never lands over a newer one. `WorkerParticipantGate` is the one seat for "may this participant act" (a queued turn as it starts, the drain, the mid-turn stop, the Continue: [internals/participants.md](internals/participants.md)); `WorkerExitClaim` is the exit claim (`POST /exit`): one lock for the kind being taken and the exit taken. Threads: the gate is loop-thread only (a turn runs on the loop; no lock), the claim is safe from any thread (its own mutex, taken after the event lock). The concerns are `include`d parts in `lib/samagotchi/worker/` (`Worker::LeavePart`: exit and leave; `Worker::WakeTurnsPart`: the turns nobody typed; `Worker::StartupPart`: the start-up settle; `Worker::SignalGracePart`: a signal's grace; `Worker::ScratchPart`: a scratch worker whose terminal left; `Worker::ChildSidePart`: a delegate child's rings, Verify fresh verdicts; `Worker::CommandQueuePart`: session commands between turns; `Worker::BlockFixesPart`: a failed block's fix, written between turns). `worker.rb` keeps the loop, the wiring, the prompt turns and the drain. They share Worker's ivars, and each header says what it writes and reads. |
716
+ | Worker | `worker.rb` (`worker_boot.rb`, `worker_idle_exit.rb`, `worker_inbound.rb`, `worker_signals.rb`, `worker_wakes.rb`, `worker_task_wakes.rb`, `task_watch.rb`, `worker_participant_gate.rb`, `worker_exit_claim.rb`) | A session's background process: builds the `Engine` and `Bridge`, runs queued turns and the wake turns nobody typed (delegate reports, a background task that finished unseen: [Finish wake](internals/background-tasks.md#finish-wake), attached context), exits when idle. A spawned one traps TERM, HUP and INT (`WorkerSignals`, installed by `WorkerBoot.run_session_loop` when `SAMAGOTCHI_WORKER_PROCESS=1`): the running turn stops as a Stop with reason `signal`, is saved, and the worker leaves (`:signal`, exit 0; a new worker only for input already queued). A running turn is checkpointed at its iteration boundaries (`TurnCheckpoint`, the `interrupted_turn` mark), and the next worker settles a turn its predecessor died in (`TurnCheckpoint.settle`). The session is saved from the turn's thread, Bridge threads and a signal's thread; `Session#save` takes a per-session lock around its snapshot and write, so an older snapshot never lands over a newer one. `WorkerParticipantGate` is the one seat for "may this participant act" (a queued turn as it starts, the drain, the mid-turn stop, the Continue: [internals/participants.md](internals/participants.md)); `WorkerExitClaim` is the exit claim (`POST /exit`): one lock for the kind being taken and the exit taken. Threads: the gate is loop-thread only (a turn runs on the loop; no lock), the claim is safe from any thread (its own mutex, taken after the event lock). The concerns are `include`d parts in `lib/samagotchi/worker/` (`Worker::LeavePart`: exit and leave; `Worker::WakeTurnsPart`: the turns nobody typed; `Worker::StartupPart`: the start-up settle; `Worker::SignalGracePart`: a signal's grace; `Worker::ScratchPart`: a scratch worker whose terminal left; `Worker::ChildSidePart`: a delegate child's rings, Verify fresh verdicts; `Worker::CommandQueuePart`: session commands between turns; `Worker::BlockFixesPart`: a failed block's fix, written between turns; `Worker::SendersPart`: who a turn's input came from; `Worker::MailPart`: peer mail; `Worker::TurnDrainPart`: the mid-turn steering drain). `worker.rb` keeps the loop, the wiring and the prompt turns. They share Worker's ivars, and each header says what it writes and reads. |
677
717
  | Session lifecycle | `session_manager/`, `worker_boot.rb`, the session sidecar files | Marker writers, derived states, lock order, crash repair and the known open windows are mapped in [Session lifecycle](internals/session-lifecycle.md). |
678
718
  | Config | `config.rb`, `config/restart_watch.rb` | Every setting as an `Entry`: env, config.yml and CLI layers ([configuration.md](configuration.md)); the notice a worker or chi web gets when config.yml changes a setting it reads only at its start. With `log.rb` it is the bottom layer: nothing it references reaches back to it, so `hosts:` and `models:` entries parse next to their types (`HostConfig.all`, `ModelSettings.all`). |
679
719
  | Paths | `paths.rb` (`Paths`) | The XDG base dirs chi's files live under, read from the env on every call: `Paths.state_home` (`$XDG_STATE_HOME`, else `~/.local/state`) and `Paths.config_home` (`$XDG_CONFIG_HOME`, else `~/.config`), both defaults under `Dir.home`; a blank variable counts as unset, a relative one is made absolute from the current directory. `Paths.tilde` shows a path with `~` for the home folder. `SessionManager` hands a spawned worker the spawner's `XDG_STATE_HOME` / `XDG_CONFIG_HOME`, when set, made absolute, so a relative one isn't read from the session's folder. |
@@ -696,7 +736,7 @@ A map of the parts the overview above doesn't name (paths under `lib/samagotchi/
696
736
  | Idle work | `idle_scheduler.rb` (`IdleScheduler`), `idle_recap.rb` (`IdleRecap`), `idle_reminders.rb` | One poller for an idle session's recap and reminders. |
697
737
  | Attached context | `context_sources.rb` (`ContextSources`), `context_poller.rb`, `context_absorber.rb`, `context_candidates.rb` (`ContextCandidates`: proposed sources, attached on the owner's mention at a turn's start, before the worker's absorb, or in a one-shot's turn; `owner_prompt.rb` decides whose words count) | External sources a session keeps fresh ([context.md](context.md)). |
698
738
  | LLM context strategies | `llm_context_strategy.rb`, `llm_context_view.rb`, `llm_context_stale.rb`, `llm_context_forget.rb` | What a request sends of the history (none, stale, forget) ([internals/llm-context-forget.md](internals/llm-context-forget.md)). |
699
- | Session chains | `session_continue.rb` (`SessionContinue`), `session_chain.rb` (`SessionChain`), `session_chain/links.rb` (`SessionChain::Links`), `session_chain/delete.rb` (`SessionChain::Delete`), `session_chain/delete_preview.rb` (`SessionChain::Delete::Preview`), `continued_from.rb` (`ContinuedFrom`) | A session that continues an earlier one. `SessionChain::Links` is the one chain walker (one listing; `latest`, `first_live`, `root`, `next_of`): `SessionChain.latest`/`.next_of`, `SessionInbox::Head` and the schedule tick all ask it. `SessionChain.opener_for` gives the text web `continue →` prefills in the new link: the previous link's own first typed message when that link continues one itself, else nil (the 201's `opener`; not saved). `SessionChain::Delete` plans and deletes a link or its chain; `Delete::Preview` supplies the web delete sheet, and `ContinuedFrom` records what a continue must undo ([sessions.md](sessions.md)). |
739
+ | Session chains | `session_continue.rb` (`SessionContinue`), `session_chain.rb` (`SessionChain`), `session_chain/links.rb` (`SessionChain::Links`), `session_chain/delete.rb` (`SessionChain::Delete`), `session_chain/delete_preview.rb` (`SessionChain::Delete::Preview`), `continued_from.rb` (`ContinuedFrom`) | A session that continues an earlier one. `SessionChain::Links` is the one chain walker (one listing, or rows given: chi web's schedule marks; `latest`, `first_live`, `root`, `next_of`): `SessionChain.latest`/`.next_of`, `InboxDelivery::Head` and the schedule tick all ask it. `SessionChain.opener_for` gives the text web `continue →` prefills in the new link: the previous link's own first typed message when that link continues one itself, else nil (the 201's `opener`; not saved). `SessionChain::Delete` plans and deletes a link or its chain; `Delete::Preview` supplies the web delete sheet, and `ContinuedFrom` records what a continue must undo ([sessions.md](sessions.md)). |
700
740
  | MCP server | `mcp_server/protocol.rb` (`McpServer::Protocol`: JSON-RPC in both revisions, no transport, no chi), `mcp_server/tools.rb` (`McpServer::Tools`: `chi_sessions`, `chi_ask`, `chi_wait`, `chi_answer` over a SessionAccess backend through `SessionAccess::Ask` and `Exchange`), `mcp_server/text.rb` (`McpServer::Text`: the results' words), `mcp_server/stdio.rb` (`McpServer::Stdio`), `mcp_server/http.rb` (`McpServer::Http`), `mcp_command.rb` (`chi mcp serve`), `web/mcp_route.rb` (`Web::McpRoute`: `POST /api/mcp`, included through SessionAccessRoutes) | chi as an MCP server ([mcp-server.md](mcp-server.md)); not the `mcp` bundle (chi as a client). Only `tools.rb` names `SessionAccess`: another front builds `Protocol.new(tools: Tools.new(access))`. The caller is a parent agent (`cli:send` / `cli:answer`, `SessionAccess::Ask#agent_line`). |
701
741
  | chi web's routes | `web/app.rb` (`Web::App`: the gate, `ROUTES`, the shared helpers), `web/request_body.rb` (`Web::RequestBody`: bounded body reads), `web/message_display.rb` (`Web::MessageDisplay`: saved messages and cards as display items, the owner show's stamped with their turns' drawings and carrying no parts (a step's ✂ marks only), the participant show's with their parts, `POST /api/render`), `web/session_show.rb` (`Web::SessionShow`: `GET /api/sessions/:id` with its `cards`, `tail` and `timing` re-reads, `GET …/output`, the timing payload), `web/session_create.rb` (`Web::SessionCreate`: `POST /api/sessions`, a continue), `web/session_control.rb` (`Web::SessionControl`: answer, command, turn and images, cancel, stop, restart, archive, delete), `web/session_access_routes.rb` (`Web::SessionAccessRoutes`: the session-command routes), `web/ask_routes.rb` (`Web::AskRoutes`: ask, wait tokens, the answer's wait, included through SessionAccessRoutes), `web/ask_create.rb` (`Web::AskCreate`: a create that answers its first turn), `web/last_ask.rb` (`Web::LastAsk`: the owner's `last`, `last_ask.json`), `web/verify_fresh_routes.rb` (`Web::VerifyFreshRoutes`: Verify fresh children), `web/working_set_routes.rb` (`Web::WorkingSetRoutes`: the working set routes), `web/viewer.rb` (`Web::Viewer`: page capabilities), `web/push_routes.rb` (`Web::PushRoutes`: `/api/push`, its subscriptions, prefs, test and presence), `web/block_renderer_routes.rb` (`Web::BlockRendererRoutes`: `GET /api/block_renderers` and one renderer's file, [internals/block-renderers.md](internals/block-renderers.md)), `web/reload_check_route.rb` (`Web::ReloadCheckRoute`: `POST /api/sessions/:id/reload_check`, the opt-in `web.reload_check`'s counts from the page's `reload_check.js`, 204 and one `reload_checked` log line, with `reload_mismatch`, its `kinds`, `excused` (ACCEPTED ids) and `explained` when the turn read otherwise after a reload; the worker's version is chi web's own view, its sidecar) | The handlers `App`'s `ROUTES` name, in the file that holds their kind; each mixin is included in `App` and reads its helpers and ivars, so `app.send(:handle_show, …)` and the specs that stub `App` methods work as before. The shared body reader caps incoming requests. |
702
742
  | Web Push | `web/push.rb` (`Web::Push`: `Runtime`, `preflight!`, the `web.push.*` settings), `web/push/crypto.rb` (`Push::Crypto`: RFC 8291 aes128gcm, RFC 8292 VAPID), `web/push/store.rb` (`Push::Store`, `Store::Sub`: `web-push/vapid.pem`, `subscriptions.json`), `web/push/client.rb` (`Push::Client`, `Client::Result`), `web/push/attention.rb` (`Push::Attention`: notify.js's rules in Ruby, shared cases in `spec/fixtures/attention_cases.json`), `web/push/presence.rb` (`Push::Presence`: the pages' "in front" reports), `web/push/notifier.rb` (`Push::Notifier`, a hub subscriber with a sender thread), `web/push_routes.rb` (`Web::PushRoutes`), `private_files.rb` (`PrivateFiles`, shared with the grants), `public/sw.js`, `public/push.js`, `public/manifest.webmanifest` | chi web pushes what the tab notifies for (approvals, questions, step-limit questions, cards, failed turns; done turns to a device that asks) to the owner's Home Screen app over an https public URL: the Notifier turns the hub's new attentions into show pushes after a hold, unless a chi web page is in front, at most 30 an hour, with one retry and a restart catch-up (`sent.json`) (each carries the keys still open, and the badge; no close push: every push shows a notification); the bell (`notifications.js`) subscribes the device, and the service worker and the page close the answered ones. See [internals/web-push.md](internals/web-push.md). |
@@ -708,7 +748,7 @@ A map of the parts the overview above doesn't name (paths under `lib/samagotchi/
708
748
  | Toolkits | `toolkit.rb` (`Toolkit`), `toolkit_binding.rb` (`ToolkitBinding`, the Engine's seam), `toolkit_command.rb` (`/toolkit`), `tools/registry.rb` (`Registry#toolkit`), `tools/tool_surface.rb` (`ToolSurface#left_out`, read by the prompt and `/toolkit`), `web/public/toolkit_chip.js` | Which registered tools a session's prompts declare: saved in the session, resolved at a turn's start (`Engine#apply_toolkit!`), named in the prompt's not-loaded line, a kit's prompt text after the appended files; `chi.toolkit` and `ctx.use_toolkit` for plugins ([configuration.md](configuration.md#toolkits)). |
709
749
  | Tool index | `tools/tool_index.rb` (`Tools::ToolIndex`), `tools/deferred_tools.rb` | `find_tools` and `call_tool`: the tools a session knows but doesn't declare one by one (an mcp bundle's servers through `chi.tool_source`, the built-ins its toolkit leaves out), searched and called by name ([plugins.md](plugins.md)). On `api: anthropic` they also go out deferred, a hit loads its matches and the model calls them by name ([internals/anthropic.md](internals/anthropic.md)). |
710
750
  | Tool output cut | `tool_output_cut.rb` (`ToolOutputCut`), `tool_output_files.rb` (`ToolOutputFiles`) | A tool's output over `max_tool_output_chars` (a `memory_read`'s: `memory.read_max_chars`, 0 = none, plus a guard at half a known window), cut by the tool's policy; an execute's whole output saved in the session's `tool_output/` folder ([internals/tool-output-limits.md](internals/tool-output-limits.md)). |
711
- | Steer delivery | `steer.rb` (`Steer`), `speaker.rb` (`Speaker`: who wrote a message, `Speaker.of`; Steer's predicates delegate to it), `delivery.rb` (`Delivery`), `steer_cut.rb` (`SteerCut`), `generation_phase.rb`, `waiting_steer.rb`, `steer_cut_after.rb` (`SteerCutAfter`), `cut_policy.rb` (`CutPolicy`) | A message for a running turn: at the next boundary, cutting a thinking-only generation, or queued for the turn's end ([internals/engine.md](internals/engine.md)). |
751
+ | Steer delivery | `steer.rb` (`Steer`), `speaker.rb` (`Speaker`: who wrote a message, `Speaker.of`, and its predicates and constants; Steer keeps the wire), `delivery.rb` (`Delivery`), `steer_cut.rb` (`SteerCut`), `generation_phase.rb`, `waiting_steer.rb`, `steer_cut_after.rb` (`SteerCutAfter`), `cut_policy.rb` (`CutPolicy`) | A message for a running turn: at the next boundary, cutting a thinking-only generation, or queued for the turn's end ([internals/engine.md](internals/engine.md)). |
712
752
  | Prompt files | `prompt_files.rb` (`PromptFiles`) | The AGENTS.md chain (root → cwd) and the appended files the system prompt carries. |
713
753
  | Model settings | `effective_model.rb` (`EffectiveModel`, `ModelChoice`), `model_lookup.rb` (`ModelLookup`: every layer's input), `model_profile.rb` (`ModelProfile`), `model_settings.rb`, `sampling_settings.rb`, `model_catalog.rb` (`ModelCatalog`), `model_notes.rb` (`ModelNotes`) | The effective model's settings as one snapshot per read, a model's prompt format, its `models:` entry, its request parameters, the pickable model rows (`chi models`, `/api/models`), the notes its prompt loads. |
714
754
  | Session settings | `session_setting.rb` (`SessionSetting`), `session_model_settings.rb` (`SessionModelSettings`), `level_setting_command.rb` (`/thinking`, `/reasoning-history`), `llm_context_command.rb`, `toolkit_command.rb`, `thinking_notices.rb` (`ThinkingNotices`) | A session's own llm_context, thinking, reasoning_history and toolkit: their chips (session state, `/stats`, `:command_ran`, the web), the commands that set them, the thinking level's notices. |
data/docs/cli.md CHANGED
@@ -18,7 +18,7 @@
18
18
  - `chi web --web-markdown` / `--no-web-markdown` — opt in to, or opt out of, sanitized Markdown rendering for completed assistant messages, the stage's asking text and a resolved question card's reply (`web.markdown`, off by default; `--no-web-markdown` turns a config's `web.markdown: true` off for this run)
19
19
  - `chi web --no-web-working-set` — turns the stage view's working set off (on by default; `--web-working-set` turns a config's `web.working_set: false` back on): what each turn brought into the model's context, in the stage and under each finished turn; `?working_set=1|0` on the page URL overrides it (see [The working set](#the-working-set))
20
20
  - `chi web --web-stage-collapsed` / `--no-web-stage-collapsed` — every session's stage starts folded to its status row, or not (`web.stage_collapsed`, off by default); a session folded or unfolded by hand keeps its own fold in that browser
21
- - `chi sessions list|stop|restart|archive|unarchive|delete|prune|clean|stats` — manage persisted sessions; `list` shows this git project's, `list --scope=all` every one, a delegated session with `↳ <parent>`, `list --archived` the archived ones too (see [Sessions](sessions.md)); one line per session (`<id> <state> <ctx> <updated_at> <text> [flags] ↳ … ↪ …`) and one footer (`N session(s) (sort=… order=…)`, or the project note) for the plain list, the `--live`/`--cwd` text and `--remote`. `stats ID` prints a session's cost, tokens and progress, and its own settings (`--set`; a `settings:` line), from a live worker's `GET stats`, else its saved `analytics.json` (`--format json` one object, with `settings`), without running a model turn. A usage error (an unknown subcommand or flag, a flag missing its value, `stop`, `restart` or `delete` with no ids, `unarchive --stop-tasks`, a bad `list --format`, `--scope`, `--sort` or `--order`, a `--days`, `--keep` or `--limit` that isn't a whole number) exits 2; an unknown or refused session exits 1
21
+ - `chi sessions list|stop|restart|archive|unarchive|delete|prune|clean|stats|migrate` — manage persisted sessions; `list` shows this git project's, `list --scope=all` every one, a delegated session with `↳ <parent>`, `list --archived` the archived ones too (see [Sessions](sessions.md)); one line per session (`<id> <state> <ctx> <updated_at> <text> [flags] ↳ … ↪ …`) and one footer (`N session(s) (sort=… order=…)`, or the project note) for the plain list, the `--live`/`--cwd` text and `--remote`. `stats ID` prints a session's cost, tokens and progress, and its own settings (`--set`; a `settings:` line), from a live worker's `GET stats`, else its saved `analytics.json` (`--format json` one object, with `settings`), without running a model turn. `migrate` moves saved sessions to the current storage format (see below). A usage error (an unknown subcommand or flag, a flag missing its value, `stop`, `restart` or `delete` with no ids, `unarchive --stop-tasks`, a bad `list --format`, `--scope`, `--sort` or `--order`, a `--days`, `--keep` or `--limit` that isn't a whole number) exits 2; an unknown or refused session exits 1
22
22
  - `chi note [--source NAME] [-m TEXT] (ID|PREFIX)... | --all` — add a context note (TEXT or stdin) to sessions: background the model sees on its next turn; it starts no turn (see [Sessions: Context notes](sessions.md#context-notes))
23
23
  - `chi broadcast [-m TEXT] [--all] [--dry-run]`, `chi broadcast log [--last N] [--format json]`, `chi broadcast deliver BROADCAST_ID (ID|PREFIX)...` — share one piece of information (TEXT or stdin) with every session it may concern, as a context note from `broadcast` (see [Broadcast](broadcast.md))
24
24
  - `chi context <add|push|ls|show|refresh|rm|mute|unmute> …` — attach live external text to sessions (a command chi runs every so often, or text pushed in); the model gets a short note when it changes and reads it with `context_read`; `chi context add <URL>` attaches a GitHub PR with the github-pr bundle; `chi context push NAME -m TEXT` (the long form is `--message TEXT`) gives a `--push` source its new text, read from stdin when no `-m` is given (see [Attached context](context.md))
@@ -909,6 +909,25 @@ object `{session_id, status, live, metrics, settings}` (`settings`: the session'
909
909
  exits 0. An unknown or ambiguous id exits 1 with `chi sessions stop`'s
910
910
  wording. See [Sessions](sessions.md#cli).
911
911
 
912
+ `chi sessions migrate [--dry-run] [--id ID]... [--json]` moves saved sessions
913
+ to the current storage format (`StorageMigration`): today one step,
914
+ `session-split-messages` v1, each session's conversation into its own file
915
+ beside `<id>.json` ([Messages file](sessions.md#messages-file)). Every session
916
+ file, archived ones too, or the ones `--id` names (an id or a unique prefix,
917
+ repeatable; one named twice converts once); one a worker holds, one being started or
918
+ one a transition holds is skipped (it converts at its own next save), as are one whose
919
+ `messages` is not a list and one deleted meanwhile (no folder left), and a run again
920
+ converts only what is left. It needs `session.split_messages` on: off, it exits 2 ("split sessions
921
+ read as empty in chi 0.201.0 and older: turn on session.split_messages first"),
922
+ writing nothing; `--dry-run` reads only and reports either way. The line says
923
+ how many were converted (or would be), the session files' size before and
924
+ after, how many were done already, skipped (by reason) and failed (each named);
925
+ `--json` prints the report. Exit 1 when one failed (its file put back as it
926
+ was; when putting it back fails too, the line says so and where its original
927
+ is: `<id>.json.premigrate` beside it, to copy back by hand), or when an `--id`
928
+ names no session (nothing converted). Local only:
929
+ `--remote` refuses it.
930
+
912
931
  **One-turn runs.** `chi -p TEXT --non-interactive` (also with `--resume ID`)
913
932
  runs its turn in this process, with no worker, and holds the session until it
914
933
  ends. Meanwhile the session is "in use by a one-turn chi --non-interactive
@@ -173,7 +173,7 @@ or `chi web` restart.
173
173
  | `system_one.host`, `system_one.model`, `system_one.timeout_ms`, `system_one.runs`, `system_one.judgments` | Next tool call or approval | Each ask reads them. |
174
174
  | `hooks`, `bundles` | Worker start | Hooks, plugins and their bundle settings load with the engine. |
175
175
  | `recap.*` | Worker start | The engine builds its recap job at start, and again when it binds a session with its own `recap.enabled` or `recap.sentences` (`--set`, see "Per-session settings") and when `/recap on\|off\|default` changes the session's own value. |
176
- | `session.idle_exit_minutes`, `session.project_env`, `session.carry_last_answer`, `session.keep_empty`, `session.max_children`, `session.delegate_reports`, `session.task_wakes`, `session.max_wakes` | Worker start or next matching lifecycle decision | Existing workers keep their idle-exit timer and project env; the other values are read for the next corresponding decision. |
176
+ | `session.idle_exit_minutes`, `session.project_env`, `session.carry_last_answer`, `session.keep_empty`, `session.split_messages`, `session.max_children`, `session.delegate_reports`, `session.task_wakes`, `session.max_wakes` | Worker start or next matching lifecycle decision | Existing workers keep their idle-exit timer and project env; the other values are read for the next corresponding decision. |
177
177
  | `session.retention_*`, `session.max_count`, `session.keep_status`, `session.sweep_interval_hours` | Next retention sweep | `chi web` sweeps on its configured schedule and on `GET /api/sessions`; `chi sessions prune` uses the values for that invocation. The sweep interval is checked on the next hub tick. |
178
178
  | `schedule.*` | Next CLI run | `chi schedule add` and `chi schedule tick` read them for that run; with `schedule.auto_tick` on, `chi web`'s hub ticks on `schedule.tick_interval_minutes`. |
179
179
  | `web.*` except `web.participants.*` and except `web.ask_dir` | `chi web` start | Restart `chi web` to change its bind address, port or page settings. |
@@ -2403,6 +2403,7 @@ column says so, a `--kebab-name` flag. The maps (`hosts:`, `models:`,
2403
2403
  | `session.project_env` | `mise` | | The commands a session's worker runs follow its project: `mise` runs them in the session folder's `mise env`, read once at worker start (`chi sessions restart` picks up a mise.toml edit); `off` doesn't ask mise: the tools keep the env of whoever started the worker (with a chi home, the home's `chi` still goes first on their PATH). See [Project env](sessions.md#project-env). |
2404
2404
  | `session.carry_last_answer` | `true` | | A continue's carry note holds the previous session's last answer after its recap; `false`: the recap only. See [Session chains](sessions.md#session-chains). |
2405
2405
  | `session.keep_empty` | `false` | | Keep sessions nothing happened in. |
2406
+ | `session.split_messages` | `false` | | Save a session's messages in their own file beside `<id>.json` (appended per save); a session read that way stays so. chi 0.201.0 and older show such a session as empty. `chi sessions migrate` converts saved sessions; see [sessions.md](sessions.md#messages-file). |
2406
2407
  | `session.max_children` | `4` | | Running delegated sessions one session may have. |
2407
2408
  | `session.delegate_reports` | `wake` | | When a delegate child ends a turn, its reply reaches the parent: `wake` runs an idle parent's turn for it, `queue` waits for the parent's next turn, `off` leaves it to `delegate_result`. |
2408
2409
  | `session.task_wakes` | `wake` | | When a background task the session started (`task_create`, an `execute` handed over at its limit) finishes and the model hasn't seen it finish: `wake` runs an idle session's turn opened by a `TASK FINISHED` note, `queue` leaves the note for the next turn, `off` leaves it to `task_wait`. See [Finish wake](internals/background-tasks.md#finish-wake). |
@@ -203,12 +203,12 @@ the "asking again" and steer-cut rows, ✂ rows and questions (with how they wer
203
203
  - **Anchored to its turn.** The store keeps a **turn log**, every id it saw at `:turn_started`, oldest first. An entry
204
204
  holds `turn_id`: the running turn's, else the log's last (nil before any); a load warning, which the Engine announces
205
205
  inside the first turn, takes the one before it. `list(messages:)` computes `turns_since` from the messages the page draws
206
- (`CardPlaces`, the snapshot's own list; a stopped session's file for `.saved`): the turn openings (`Steer.turn_opening?`, as
206
+ (`CardPlaces`, the snapshot's own list; a stopped session's file for `.saved`): the turn openings (`Speaker.turn_opening?`, as
207
207
  the page's `TURN_PROMPT` and the recap count) after the last one whose id is in the log at or before the entry's, else from
208
208
  the first one whose id is later in the log, else 0. The log only orders; the messages count. So a turn with no opening (a
209
209
  reminder, a Continue, a failed or rolled-back one, a prompt stopped before the model) moves nothing, a wake's note does, and
210
210
  an opening with no turn id (`/continue no`'s reason, which carries an `opening_id` of its own instead, `TurnFlow#abort_continue!`)
211
- counts as on the page. KernelLoop's Qwen recovery line (kind `recovery`, `Steer.recovery?`) is a row of its turn, no opening:
211
+ counts as on the page. KernelLoop's Qwen recovery line (kind `recovery`, `Speaker.recovery?`) is a row of its turn, no opening:
212
212
  the page draws nothing for it (`MessageDisplay`), as live. Nothing orders such an opening
213
213
  against an entry, so the store reads the session's messages (its `messages:` lambda) when an entry is shown between turns, and
214
214
  at the turn's end for what a running turn showed that isn't its own: `past_idless` is how many of them, right after the opening
@@ -219,7 +219,7 @@ the "asking again" and steer-cut rows, ✂ rows and questions (with how they wer
219
219
  comes mid-turn but isn't the turn's (an anytime command's, such as `/btw`) goes after that turn (`during`), and so does a
220
220
  between-turns notice. A card with an earlier card's id replaces it in place and keeps its anchor. A `list` with no messages
221
221
  (`?cards=1`'s bodies, `chi bundle try`'s trace) has no `turns_since` and no `opening_id`.
222
- - **The stamp.** Next to `turns_since`, an entry lists `opening_id` (`CardPlaces#opening_of`, one `Steer.opening_stamp` rule with the recap's): the id of the opening its count
222
+ - **The stamp.** Next to `turns_since`, an entry lists `opening_id` (`CardPlaces#opening_of`, one `Speaker.opening_stamp` rule with the recap's): the id of the opening its count
223
223
  reaches, the one it comes after: a prompt's `turn_id` (a wake note's too), or `/continue no`'s reason line's `opening_id`. It is
224
224
  resolved at `list` time from the same anchor (an entry's own turn often has no bubble: a Continue, a failed or rolled-back turn),
225
225
  so the stamp and the count always name one place, and the page finds it by the bubble (`card_stamps.js`: `data-turn-id`, or `data-opening-id` on a wake's note or a reason line), not by counting
@@ -700,7 +700,7 @@ compatibility from its version. `Bridge::FEATURES` advertises:
700
700
  | `working_set_item` | `GET /session/:id/working_set/item` answers one item's timeline (the running turn's mid-turn), so chi web asks for it instead of the whole snapshot. |
701
701
  | `peer_mail` | The worker takes a peer's messages from the mailbox (`WorkerInbound#absorb_mail`, [peers.md](peers.md)); `chi peer pair` and `say` refuse a live worker without it ("restart the session"), read through `WorkerLink.live_features`. |
702
702
  | `model_mark` | A `/model` switch leaves its line (`ModelSwitchMark`, a between-turns hook notice of hook `model`). The page leaves a picked switch's command lines out only then (`model_switch.js workerMarks`); an older worker keeps them, and draws no mark. |
703
- | `agent_sender` | The worker reads an agent's id (`agent:<name>`: a driver's or a visitor's turn, `Visitor`). Without it `SessionManager#deliver_turn_now` sends `cli:send` instead (compat shim agent_client_id), also on the file path while a worker holds the session; chi web lists it in `/api/info` too, for `SessionAccess::Remote#sent_id`. |
703
+ | `agent_sender` | The worker reads an agent's id (`agent:<name>`: a driver's or a visitor's turn, `Visitor`). chi web lists it in `/api/info` too. |
704
704
  | `ask_session` | The worker runs another session's question (`session:<id8>`) as a visitor's turn. Without it the question is refused (409 `ask_unavailable`), and its file is not written while a worker may hold the session. |
705
705
 
706
706
  `chi web`'s `GET /api/sessions/:id/stream` proxies this bridge
@@ -121,7 +121,10 @@ StandardError in run_turn:
121
121
  ModelProfile::MissingModel: the user's to change, no error_kind); else chi's own (TurnEndings.chi_error?):
122
122
  "chi error: <message's first line> (<Class>); details in samagotchi.log", logged ERROR turn chi_error with its
123
123
  backtrace (Log.exception). retryable stays unset for it; a parent's wait, ParentReport and a schedule's last
124
- result read error_kind "chi_error" as any other kind.
124
+ result read error_kind "chi_error" as any other kind. The note's text is the model's; beside it the note
125
+ carries `failed:` (the summary) and, when its work stayed, `kept:` (the steps): display only
126
+ (`AnswerDisplay::DISPLAY_ONLY`, ChatLoop's allowlist keeps them, never sent), read first by
127
+ `TurnNote.failure_summary` (`chi send --wait`) and `Bridge::TurnRanges`, the words for an older chi's note.
125
128
 
126
129
  Before the Engine's turn (Worker#run_engine_turn: begin_turn, the checkpoint, the running save):
127
130
  → session still running, no :turn_failed sent: Engine#fail_turn_not_begun sets it idle, records last_turn and
@@ -603,7 +606,7 @@ Turn events (the main ones; `events.rb` keeps the shared sets):
603
606
  | `:guardrail_warning` | a guardrails line | `{message}` |
604
607
  | `:turn_completed` | normal end | `{turn_id, result, turn_summary, display_pending}`, plus `verify`, `verdict`, `revises` when there are; the SSE frame omits `result` |
605
608
  | `:turn_canceled` | Stop, hook stop, Ctrl-C, signal | `{turn_id, cancellation_reason, cancelled_by?, duration_ms}` |
606
- | `:turn_failed` | an error (also before a turn began: `Engine#fail_turn_not_begun`, no `:turn_started`) | `{turn_id, error_class, message, duration_ms, error_kind?, retryable?, host?, summary?}` |
609
+ | `:turn_failed` | an error (also before a turn began: `Engine#fail_turn_not_begun`, no `:turn_started`) | `{turn_id, error_class, message, duration_ms, error_kind?, retryable?, host?, summary?, error_reason?}` (`error_reason: :model_not_served` beside `bad_request` when the host doesn't serve the model; `LastTurn` keeps it and the host as `error_reason` / `error_host`, `TurnEndings#failure_facts`) |
607
610
  | `:answer_display` | after the after_turn hooks (observers only) | `{display, refs?}` |
608
611
 
609
612
  ### Origins and authors
@@ -618,14 +621,14 @@ form (`#empty?`, `#wire` nil), so events and hooks carry no origin for it. The b
618
621
  when someone other than the owner wrote it (stamped by chi web from the request's `Web::Principal`). **An owner's turn
619
622
  has no `author` anywhere**: not in its input file, its origin or the session.
620
623
 
621
- Where a participant's author (`"p:<id>"`; `Speaker.participant_author?`, `Steer`'s delegates to it) goes (the model is in
624
+ Where a participant's author (`"p:<id>"`; `Speaker.participant_author?`) goes (the model is in
622
625
  [participants.md](participants.md)):
623
626
 
624
627
  - **The opening message** gets `author` and `author_name` (`Engine#author_fields`; the name from
625
628
  `participants.json` at the turn's start, left out when unnamed). Merged input and steers carry the same keys,
626
629
  grouped by sender and author so a participant's lines never share the owner's message (`Steer::Line#author`).
627
- Assistant and tool messages carry none: `Steer.author_at(messages, index)` resolves by position. `ChatLoop#plain`
628
- keeps the keys (`Steer::AUTHOR_KEYS`).
630
+ Assistant and tool messages carry none: `Speaker.author_at(messages, index)` resolves by position. `ChatLoop#plain`
631
+ keeps the keys (`Speaker::AUTHOR_KEYS`).
629
632
  - **The wire**: such a message goes out under its participant header (`Steer.wire_text`: the pair one, or the review one for an older chi's; prompt-caching.md).
630
633
  Saved raw.
631
634
  - **`Session#last_turn.author`** and the analytics record's `author` (`SessionMetrics`); a Continue keeps the offer
@@ -726,7 +729,7 @@ model-facing copy (`strip` / `strip_all`: hooks' `messages:`, the recap, `ctx.me
726
729
 
727
730
  **The saved-keys rule.** `ChatLoop#plain` rebuilds every kept message from fixed key lists, earlier turns'
728
731
  included: a saved message field the wire needs must be listed there (or in `ContextNote::KEYS`,
729
- `Steer::AUTHOR_KEYS`, `ToolResponse::SAVED_KEYS`), or it is gone after its turn and the chat wires' prefix breaks.
732
+ `Speaker::AUTHOR_KEYS`, `ToolResponse::SAVED_KEYS`), or it is gone after its turn and the chat wires' prefix breaks.
730
733
  `spec/llm/chat_loop_saved_keys_spec.rb` fails on such a field; its first turn carries a visitor's `source` and an
731
734
  ask's `reply_for` / `reply_line`.
732
735
 
@@ -52,7 +52,14 @@ create virtual table chunks using fts5(title, body, tokenize='porter unicode61')
52
52
  create table meta(k text primary key, v text); -- the schema version
53
53
  ```
54
54
 
55
- A schema version other than `Store::SCHEMA_VERSION` drops the file and builds it again (re-creatable data). Writes
55
+ An older schema version than `Store::SCHEMA_VERSION` drops the file and builds it again (re-creatable data). A
56
+ **newer** one (a newer chi's index; its workers and this one's share a catalog) is left as it is (H3, audit r24): the
57
+ version is read first with `pragma query_only=1` (`Store#schema_version`, `#newer?`: a number above this chi's), so
58
+ nothing is written, made or `rm_f`ed; `Store#ensure_schema!` raises `Store::NewerSchema` with one `Log.warn`
59
+ (`knowledge_newer_index`), so the refresh fails on its source (`last_error`, the age line: "a newer chi's index … restart
60
+ this session on the newer chi") and the meaning pass stops; the search still reads the index as it is. `Refresh#sweep`,
61
+ `knowledge_remove` and a moved source's `clear_rows` delete no row in it (a removed source's rows stay, filtered at
62
+ search). Writes
56
63
  are `begin immediate` transactions of at most 1.5 MB of JSON each (the 2 s busy timeout), under the catalog's
57
64
  `index.lock`.
58
65
 
@@ -77,7 +84,7 @@ $XDG_STATE_HOME/samagotchi/plugins/knowledge/ (ctx.data_dir, realpath'd onc
77
84
  - `Catalog.locate`: `catalog: NAME` (`[a-z0-9][a-z0-9-]{0,31}`, not `system` or `projects`) → `catalogs/NAME`; else
78
85
  `ctx.project.key` → `projects/<key>` (a key that isn't a safe path segment becomes `p_<sha256 prefix>`); else
79
86
  `system/`.
80
- - `catalog.json` holds the sources (name, kind, location, max_age, why, globs, refreshed_at, last_error, items,
87
+ - `catalog.json` holds the sources (name, kind, location, max_age, why, globs, `gen` (stamped by each add, checked by `Refresh#current!`), refreshed_at, last_error, items,
81
88
  chunks, skipped counts; a github source's `clone`, a sessions or context source's `project_root`, `listed_at`),
82
89
  `removed_defaults`, `seeded` and notes. It is read without a lock and written
83
90
  (`AtomicFile.write`, 0600) only under `index.lock`, which every index write takes too.
@@ -101,6 +108,15 @@ $XDG_STATE_HOME/samagotchi/plugins/knowledge/ (ctx.data_dir, realpath'd onc
101
108
  - **Locks:** `sources/<name>.lock`, `flock` without waiting, per refresh: one held elsewhere (another worker) is
102
109
  skipped (`refreshing elsewhere`). `index.lock` exclusive around each write transaction and `catalog.json` write.
103
110
  Readers take none.
111
+ - **A source changed under a refresh** (H2, audit r24): `knowledge_add` stamps the source a new `gen` (a random hex;
112
+ added again, it also drops `refreshed_at`, so it is due), and `knowledge_remove` deletes its rows and its record under
113
+ one hold of `index.lock`. A refresh keeps the `gen` it started with and checks it, under `index.lock`, after its
114
+ listing, before each index write (`Refresh#current!`) and in its record: a source removed or added again since (an add
115
+ from another project, other globs) stops the refresh (`Refresh::Dropped`, state `:elsewhere`) with nothing put, deleted
116
+ or recorded, so no row of the removed source comes back and no `listed_at` lands on the new record; the next search
117
+ refreshes the new one. A github clone the stopped fetch renamed into place goes (`GithubAdapter.drop_clone`, the `dropped:`
118
+ callable) unless a source still names it. A source from before `gen` has none (nil matches nil); an older bundle's
119
+ worker neither stamps nor checks it. No add or remove waits on a source lock.
104
120
  - **Diff:** an adapter lists items with a `sig` (a file's `mtime:size`, a blob sha, a session's `updated_at`, a
105
121
  snapshot's revision); only items whose sig changed are read and re-chunked, the gone ones deleted by `chunk_map`.
106
122
  An adapter with `#gone(old_keys)` lists only what changed (the sessions one, since the source's `listed_at`, the
@@ -161,8 +177,8 @@ $XDG_STATE_HOME/samagotchi/plugins/knowledge/ (ctx.data_dir, realpath'd onc
161
177
  prompt, the model's answers and any line merged into it (a live snapshot's merged input has no kind and no
162
178
  `turn_id`, so it never ends one: the rule drops more, never less); a participant's line merged into the owner's
163
179
  turn goes alone. An item's sig is `"<RULE>:<updated_at>"` (`SessionsAdapter::RULE`, now `"2"`). **The old-rule
164
- sweep:** every search that selects a sessions source (`Plugin#sweep`, whatever the source's age, project or the
165
- search's budget) deletes its rows whose sig lacks the prefix (indexed before the rule, a participant's text with
180
+ sweep:** every search or add of the catalog (`Refresh#sweep`, the end of each `Refresh#run`, over every sessions
181
+ source of the catalog, whatever the call selected, the source's age, project or the call's budget) deletes its rows whose sig lacks the prefix (indexed before the rule, a participant's text with
166
182
  them; `#sweep_old_rule`, under the catalog lock) and clears its `listed_at`; `Plugin#adapter_for` lists in full
167
183
  while any such row is left, so only those sessions are re-chunked, and a listing cut short stays full until one
168
184
  completes. A stale worker on the older bundle writes unprefixed sigs again, swept at the next search. Every message's text and the
@@ -174,8 +190,12 @@ $XDG_STATE_HOME/samagotchi/plugins/knowledge/ (ctx.data_dir, realpath'd onc
174
190
  (`ctx.sessions.read` raising) keeps the source's `listed_at` at its `updated_at` (`Refresh`: the min of the
175
191
  listing's start and each unread item's), so the next listing reads it again. A named catalog's source added again
176
192
  from another project (its `project_root` changes) drops its rows first: they are the old project's, which no id
177
- sweep removes (`present_ids` is every saved session, not one project's). **The id sweep:** every search that
178
- selects a sessions source deletes the rows of ids no longer in `present_ids` (~2 ms) before the query, and the
193
+ sweep removes (`present_ids` is every saved session, not one project's). **The id sweep:** the same `Refresh#sweep`
194
+ deletes the rows of ids no longer in `present_ids` (~2 ms, plus one `sqlite3` run for the schema check per call of
195
+ a catalog with a sessions source) before the query: a search of the docs alone, or a `knowledge_add`, purges a
196
+ deleted session's text too (H4 (a), audit r24; before, only a search selecting the sessions source did). Not on a
197
+ participant's turn (their search reads no chi source). A catalog no one searches or adds to keeps the rows until
198
+ then: there is no purge at delete time. The
179
199
  searching session's own rows are excluded in the query (`Store#search(skip:)`: a project catalog is shared, so
180
200
  another session indexes yours). Measured here: listing 407 session files 0.2 s; `Session.load` of this project's 171
181
201
  sessions 0.3 s (15,556 user/model messages, 1.4 M chars; `ctx.sessions.read` also asks a running worker for its
@@ -108,7 +108,7 @@ Bridge's `TurnAccumulator#current_messages`) leaves tool calls out. A move shows
108
108
  - **Backing** (`Objectives::Backing`, `objectives_backing.rb`): what the move's own turn ran before it, derived by the
109
109
  harness, since the model sees run ids only with the forget layer on and can't cite a run in general; its `evidence`
110
110
  stays free text. `moves_in` builds it from the same `paired_runs`: the runs after the nearest turn opening before the
111
- move's entry (`Steer.turn_prompt?`, what bounds a turn's slice), up to the move, those before it in its own batch
111
+ move's entry (`Speaker.turn_prompt?`, what bounds a turn's slice), up to the move, those before it in its own batch
112
112
  too. `edits` counts the edit and write runs that succeeded (not a failed, denied or interrupted one); `command` is the
113
113
  last finished `execute` or `task_wait` run's `ok` or `failed`, read on the text after `ToolActivity.saved_result_text`
114
114
  (with `tool_activity_status`, so a grep that found nothing is `ok`). No command: one the guardrails denied, stopped or
@@ -378,7 +378,7 @@ not a canceled or exhausted one), on the turn's thread after `end_turn` and befo
378
378
  active item; `pending_payload` is a file read), then the turn: not a `--non-interactive` run (`Engine#interface ==
379
379
  :non_interactive`: its origin can't tell, `ClientId.human?(nil)` is true), the owner's (`OwnerPrompt.turn?`: not a
380
380
  participant's; a person's prompt or a wake), and the newest turn of the stored conversation (after
381
- its last `Steer.turn_prompt?` entry) has at least one run that is work (`Objectives::Backing.work?`: an edit or write that
381
+ its last `Speaker.turn_prompt?` entry) has at least one run that is work (`Objectives::Backing.work?`: an edit or write that
382
382
  succeeded, an execute that finished ok, the page's no-move rule) and no objectives call that recorded a move. The stored
383
383
  conversation is copied on the turn's thread; the request goes on a thread of its own kind (`SideJudgments#start`), so the
384
384
  turn's end never waits, and a turn while one is still in flight starts none.
@@ -192,7 +192,7 @@ all `:owner`: a participant's token gets 403 `not_permitted` (`participant_gate_
192
192
  |---|---|
193
193
  | `GET /api/pages` | `{pages: [{name, title, state, ran_at, failed_at, changed, error_line, bundle}]}`, by name (`Store.list`) |
194
194
  | `GET /api/pages/NAME` | the page (below); 404 `page_missing` with no script. Runs nothing |
195
- | `POST /api/pages/NAME/run` | `Launch.run(name, timeout: 30, cancelled: -> { !@server_running.call }, params:, strict: false)` inside the request; the page as after the run, with `stderr` (its last 2 KB) when it failed. An optional body `{"params": {"days": "30"}}` (no body: no values, as an older cached app.js posts); the raw body is read, since `parse_json` answers nil for an empty body and bad JSON alike: one that isn't an object, or whose `params` isn't a Hash of String => String, is 400 `bad_params`. 409 `page_busy`, 404 `page_missing`, 503 `server_stopping` (chi web's stop ended it: "the run was stopped") |
195
+ | `POST /api/pages/NAME/run` | `Launch.run(name, timeout: 30, cancelled: -> { !@server_running.call }, params:, strict: false)` inside the request; the page as after the run, with `stderr` (its last 2 KB) when it failed. An optional body `{"params": {"days": "30"}}` (no body: no values, as an older cached app.js posts); the raw body is read, since `parse_json` answers nil for an empty body and bad JSON alike: one that isn't an object, or whose `params` isn't a Hash of String => String, is 400 `bad_params`, as are more than `Pages::MAX_PARAMS` params or a value over `Pages::MAX_CHOICE` characters (the values go into one argv JSON, `Launch#command`: a huge body would fail the spawn, E2BIG, a 500; the caps are what a script could declare anyway). 409 `page_busy`, 404 `page_missing`, 503 `server_stopping` (chi web's stop ended it: "the run was stopped") |
196
196
  | `DELETE /api/pages/NAME` | `Store.remove`: `{removed: NAME}`; 409 `page_busy`, 409 `page_bundled` (a bundle's page, `FromBundle`), 404 `page_missing` |
197
197
 
198
198
  The page: `{name, title, state, ran_at, duration_ms, changed, bundle, changed_after_failure, script_changed_at, error:
@@ -231,7 +231,9 @@ a tap, posted as the body; a page with no params posts exactly `{method: "POST"}
231
231
  choice is disabled; the view's `asked` marks the tapped one pending. `asked` is the view's own memory: kept after a
232
232
  failed answer (the failure line and Copy the error name the asked choices that differ from the kept result's:
233
233
  `failureParts(page, asked)`, `errorCopy(page, stderr, asked)`), cleared by a good answer, a refused run and another
234
- page; nothing stored, so a reload reads the line as stored. A page reopened while its run goes has `running` from
234
+ page; nothing stored, so a reload reads the line as stored. A good answer whose params differ from what was asked
235
+ (the script no longer has a choice: the lenient run took the default) toasts what ran instead
236
+ (`ranInstead`: "Ran Period: 7 days: 90 days is no longer a choice"; `askedText` finds the differing ones). A page reopened while its run goes has `running` from
235
237
  the `runs` map and no `asked`: disabled, no pending mark.
236
238
 
237
239
  **The list is live, a page isn't.** chi web's session hub stats the scripts folder (`Pages.scripts_dir`) once a tick
@@ -837,7 +837,7 @@ means the owner: a turn or session with no author keys reads as the owner's and
837
837
 
838
838
  - **Messages.** A participant's opening message is saved raw with `author`, `author_name` (the name the sidecar gave
839
839
  the participant when it was written) and `participant_mode` (`"pair"` for a pair turn, set when `Engine#run_turn` builds it, before any request carries it; a turn this chi refuses gets none). Merged input and
840
- steers carry `author` and `author_name`; assistant and tool messages carry none (`Steer.author_at` resolves a
840
+ steers carry `author` and `author_name`; assistant and tool messages carry none (`Speaker.author_at` resolves a
841
841
  turn's author by position).
842
842
  - **The header.** On the wire (both loops, and so the Messages adapter) such a message is led by one line selected
843
843
  from its `participant_mode`; a missing stamp on an older message means `review`:
@@ -155,7 +155,7 @@ starts without it.
155
155
  which posts `…/peers/NAME/say` with its `wait`: chi web waits, and its read timeout is the wait plus 30 s).
156
156
 
157
157
  0. **The link it runs on** (`Local#peer_head`): the id said to, or, when it is archived, its chain's first live
158
- link (`SessionChain::Links#first_live`, `SessionInbox::Head`'s walk; only an archived id lists the sessions).
158
+ link (`SessionChain::Links#first_live`, `InboxDelivery::Head`'s walk; only an archived id lists the sessions).
159
159
  Every step below is keyed on that link, never on the id asked (its `taken`, its receipts, its worker, its hold),
160
160
  and a received say's `PeerSay#forwarded_to` names it (on the wire; the line ends `· session continued as <id8>:
161
161
  answer there`; an older client drops it and prints the old line). One hop: a link continued again meanwhile is
@@ -178,7 +178,7 @@ which posts `…/peers/NAME/say` with its `wait`: chi web waits, and its read ti
178
178
  refusal that sends the peer to pair again. The feature probe before and the receipt wait after stay outside the
179
179
  hold; the delivery's worker start (`resume_session`, a spawn) is inside it. A delivery the row's own hold
180
180
  refused (`Hold.under`) reads as `:continued` (its successor named) or `:busy`, not as no such session.
181
- 3. `SessionInbox.deliver(:peer)` (`WakePolicy::ROWS[:peer]`, the push row; `START_EVENTS[:peer] =
181
+ 3. `InboxDelivery.deliver(:peer)` (`WakePolicy::ROWS[:peer]`, the push row; `START_EVENTS[:peer] =
182
182
  :peer_woke_session`): a session gone or being deleted refuses before its block writes. Inside the block:
183
183
  the lock, the serial, the write, the trim. The block's "asks for a worker" is the message's own `wake`: no
184
184
  `context.wake`, no 10-minute window.
@@ -251,11 +251,13 @@ why a wake can't run: `:queued`, `:exit`, `:leaving`, `:before_turn` (nil: it ma
251
251
  - `settle_open`, at every worker start: a receipt left `woke` or `read` (a crash cut its turn) ends
252
252
  `failed`.
253
253
 
254
- Each of the four that changed a receipt writes the file, then calls its `on_change` (one place:
255
- `PeerReceipts#write_changed`); the worker's (`Worker#peer_receipts_changed`) announces `:chips_updated` with
256
- `peers: true`, and an open page reads `GET …/peers` again (the chip's list: held, read, ended). A call that changed
257
- none writes and announces nothing. A turn's end is written after its `turn_completed`, so the page's `touch()` on
258
- that event can't show it: this event does.
254
+ Each of the four that changed a receipt writes the file, then calls its `on_change`; the worker's
255
+ (`Worker#peer_receipts_changed`) announces `:chips_updated` with `peers: true`, and an open page reads `GET …/peers`
256
+ again (the chip's list: held, read, ended). Three go through one place (`PeerReceipts#write_changed`); `#absorbed`
257
+ writes inside its own rescue (a write failure rolls the book back and raises) and calls `on_change` after it, so an
258
+ error from the announcer can't roll the in-memory book back behind the file — the next write would then drop the
259
+ receipts the file has. A call that changed none writes and announces nothing. A turn's end is written after its
260
+ `turn_completed`, so the page's `touch()` on that event can't show it: this event does.
259
261
 
260
262
  The last 20 receipts per peer are kept; a `held` or `noted` one is never trimmed.
261
263