samagotchi 0.163.0 → 0.165.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 (104) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +77 -1
  3. data/docs/architecture.md +7 -5
  4. data/docs/bundles.md +4 -2
  5. data/docs/cli.md +23 -11
  6. data/docs/configuration.md +5 -1
  7. data/docs/guardrails.md +13 -16
  8. data/docs/internals/block-renderers.md +3 -1
  9. data/docs/internals/bridge.md +4 -3
  10. data/docs/internals/bundles.md +4 -2
  11. data/docs/internals/inline-widgets.md +13 -3
  12. data/docs/internals/remote-sessions.md +7 -2
  13. data/docs/internals/web-frontend.md +36 -9
  14. data/docs/memory.md +12 -7
  15. data/docs/plugins.md +6 -4
  16. data/docs/releasing.md +6 -2
  17. data/docs/scheduling.md +25 -3
  18. data/docs/sessions.md +9 -6
  19. data/docs/sub-agent.md +11 -0
  20. data/docs/testing.md +28 -4
  21. data/lib/samagotchi/block_renderers.rb +14 -7
  22. data/lib/samagotchi/bridge/card_store.rb +2 -1
  23. data/lib/samagotchi/bridge/turn_accumulator.rb +7 -8
  24. data/lib/samagotchi/bridge.rb +45 -3
  25. data/lib/samagotchi/bundle_command/installed_check.rb +2 -1
  26. data/lib/samagotchi/bundles/inline-widgets/manifest.yml +2 -2
  27. data/lib/samagotchi/bundles/inline-widgets/plugin.rb +8 -4
  28. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  29. data/lib/samagotchi/chi_home.rb +44 -2
  30. data/lib/samagotchi/cli/parent_wait.rb +5 -1
  31. data/lib/samagotchi/client_id.rb +34 -3
  32. data/lib/samagotchi/compat.rb +36 -0
  33. data/lib/samagotchi/context_command.rb +3 -0
  34. data/lib/samagotchi/context_providers.rb +5 -6
  35. data/lib/samagotchi/context_sources.rb +2 -2
  36. data/lib/samagotchi/continue_intent.rb +93 -0
  37. data/lib/samagotchi/events.rb +4 -4
  38. data/lib/samagotchi/extension_load.rb +2 -1
  39. data/lib/samagotchi/guardrails/child_boundary.rb +7 -27
  40. data/lib/samagotchi/guardrails/rules.rb +11 -9
  41. data/lib/samagotchi/guardrails/targets.rb +3 -4
  42. data/lib/samagotchi/inline_widgets.rb +16 -1
  43. data/lib/samagotchi/memory_bundle/provenance.rb +46 -4
  44. data/lib/samagotchi/memory_bundle/status.rb +2 -1
  45. data/lib/samagotchi/memory_command.rb +3 -0
  46. data/lib/samagotchi/memory_orphans.rb +4 -7
  47. data/lib/samagotchi/memory_paths.rb +64 -7
  48. data/lib/samagotchi/memory_usage.rb +1 -1
  49. data/lib/samagotchi/message_parts.rb +13 -0
  50. data/lib/samagotchi/note_command.rb +3 -6
  51. data/lib/samagotchi/parent_report.rb +3 -2
  52. data/lib/samagotchi/plugin/sessions.rb +4 -2
  53. data/lib/samagotchi/project_command.rb +4 -1
  54. data/lib/samagotchi/project_id_clash.rb +37 -26
  55. data/lib/samagotchi/project_init.rb +24 -7
  56. data/lib/samagotchi/reply_wait/poll.rb +2 -1
  57. data/lib/samagotchi/schedules.rb +124 -106
  58. data/lib/samagotchi/send_command/parent_gate.rb +8 -5
  59. data/lib/samagotchi/send_command.rb +203 -45
  60. data/lib/samagotchi/session.rb +3 -2
  61. data/lib/samagotchi/session_access/local.rb +25 -2
  62. data/lib/samagotchi/session_access/remote.rb +40 -4
  63. data/lib/samagotchi/session_chain/links.rb +109 -0
  64. data/lib/samagotchi/session_chain.rb +7 -19
  65. data/lib/samagotchi/session_continue.rb +143 -57
  66. data/lib/samagotchi/session_inbox_delivery.rb +94 -28
  67. data/lib/samagotchi/session_manager/delivery.rb +106 -18
  68. data/lib/samagotchi/session_manager/removal.rb +13 -7
  69. data/lib/samagotchi/session_manager.rb +1 -0
  70. data/lib/samagotchi/session_retention.rb +20 -10
  71. data/lib/samagotchi/session_setup.rb +31 -1
  72. data/lib/samagotchi/state_format.rb +12 -8
  73. data/lib/samagotchi/terminal_ui/attach_launcher.rb +6 -7
  74. data/lib/samagotchi/terminal_ui.rb +20 -9
  75. data/lib/samagotchi/tools/delegate.rb +2 -1
  76. data/lib/samagotchi/verify_fresh.rb +4 -1
  77. data/lib/samagotchi/version.rb +1 -1
  78. data/lib/samagotchi/web/message_display.rb +1 -9
  79. data/lib/samagotchi/web/public/activity.js +2 -2
  80. data/lib/samagotchi/web/public/app.js +13 -13
  81. data/lib/samagotchi/web/public/apple-touch-icon.png +0 -0
  82. data/lib/samagotchi/web/public/bar_fold.js +293 -0
  83. data/lib/samagotchi/web/public/card.js +1 -1
  84. data/lib/samagotchi/web/public/composer_mode.js +5 -7
  85. data/lib/samagotchi/web/public/favicon.svg +1 -1
  86. data/lib/samagotchi/web/public/icons/chi-180.png +0 -0
  87. data/lib/samagotchi/web/public/icons/chi-192.png +0 -0
  88. data/lib/samagotchi/web/public/icons/chi-512.png +0 -0
  89. data/lib/samagotchi/web/public/index.html +132 -65
  90. data/lib/samagotchi/web/public/info_bar.js +28 -16
  91. data/lib/samagotchi/web/public/info_bar_model.js +70 -1
  92. data/lib/samagotchi/web/public/inline_widgets.js +4 -1
  93. data/lib/samagotchi/web/public/more_sheet.js +98 -40
  94. data/lib/samagotchi/web/public/stage_view.js +3 -1
  95. data/lib/samagotchi/web/public/stream_handlers.js +1 -1
  96. data/lib/samagotchi/web/public/turn_events.js +0 -122
  97. data/lib/samagotchi/web/public/turn_model.js +1 -1
  98. data/lib/samagotchi/web/public/widget_picks.js +18 -3
  99. data/lib/samagotchi/web/public/widget_walk.js +14 -4
  100. data/lib/samagotchi/web/session_access_routes.rb +8 -1
  101. data/lib/samagotchi/web/session_control.rb +15 -2
  102. data/lib/samagotchi/web/session_create.rb +4 -2
  103. data/lib/samagotchi/web/update_check.rb +27 -8
  104. metadata +4 -1
data/docs/plugins.md CHANGED
@@ -341,9 +341,9 @@ is what `targets:` says:
341
341
  it when the call writes, never when it only reads (a read's paths are
342
342
  `path:` rule material, not a write); a tool without it is judged as
343
343
  today.
344
- - `command:`: a shell command the call runs; `command:` rules match it, and
345
- a delegate child's boundary checks where it runs and whether it changes
346
- what every checkout shares (as for `execute`).
344
+ - `command:`: a shell command the call runs; `tool: shell` and `command:`
345
+ rules match it, and a delegate child's boundary checks it as it does
346
+ `execute` and `task_create`.
347
347
  - `cwd:`: where it runs, for the repo root and relative paths.
348
348
  - `acts_as:`: the tool a call stands for, when the tool runs other tools
349
349
  (chi's `call_tool`, which calls a tool a [source](#chitool_sourcecall-acts_as-label-wait-prefix) published). Rules keyed by that tool's name match the
@@ -1260,7 +1260,9 @@ ctx.sessions.review(subjects: ["docs/plan.md"], seed: handoff) # => a review se
1260
1260
  review session's id. The test kit's `bundle.sessions` answers `review-1`,
1261
1261
  `review-2`…
1262
1262
  - `send(id, text)` sends a user message to a session (an id or a unique
1263
- prefix); it runs as a turn, and a stopped session is woken. It waits up to
1263
+ prefix); it runs as a turn, and an idle session is woken. A session its
1264
+ owner stopped or archived is not: `Error` (`session_stopped` /
1265
+ `session_archived`), nothing sent. It waits up to
1264
1266
  5 s for the session's worker, so call it from an anytime command or a
1265
1267
  thread of your own, never from a tool or hook of a running turn. A
1266
1268
  session a `--non-interactive` one-shot has can't take it.
data/docs/releasing.md CHANGED
@@ -98,9 +98,13 @@ The agent does each step and stops where the user has to say yes.
98
98
  each one's version, none for a profile already bumped since the last tag),
99
99
  which it names in the CHANGELOG's "Update with `chi update`" line, and the
100
100
  SINCE entries it moved out of their `# Unreleased` comments. It also records
101
- the release's session, bridge, cards, schedules and bundle state under
101
+ the release's session, bridge, cards, schedules and bundle state, and a
102
+ session's input file, note, continue intent and stop marker and a bundle's
103
+ install journal, under
102
104
  `spec/compat/X.Y.Z/`; commit those samples with the release so the next
103
- release's reader spec checks them as N-1 data.
105
+ release's reader spec checks them as N-1 data. The new VERSION may pass a
106
+ compat shim's `remove_after` (`Compat::SHIMS`): `spec/compat_spec.rb` then
107
+ names it, and the shim goes (or its date moves) before the release.
104
108
  5. **Check.** Add all release files, including the new compatibility corpus, then run it:
105
109
  `git add -A && git commit -m "Release X.Y.Z"` and `bundle exec rake release:check`.
106
110
  Fix anything it finds in new commits and run it again.
data/docs/scheduling.md CHANGED
@@ -62,6 +62,10 @@ a participant's review or pair turn is denied them ([guardrails.md](guardrails.m
62
62
  `head` through the chain: once the session is continued — by a chain schedule or
63
63
  by a `chi send --continues` — the turn goes to the new link, not to the archived
64
64
  anchor the schedule was made against.
65
+ Both modes resolve the **chain's end** (`SessionChain::Links#latest`), not the
66
+ first live link a `chi send` takes: a chain firing can only continue the end, and
67
+ an archived end (a chain you retired) fails the firing instead of being brought
68
+ back as a send would.
65
69
 
66
70
  A `scratch` session is refused at `add`: it is deleted when its terminal leaves.
67
71
  A prompt is checked at `add` too — non-empty and at most 16 KiB
@@ -103,6 +107,13 @@ time zones.
103
107
 
104
108
  A cron tick cannot read a worker's memory, so the tick has two paths.
105
109
 
110
+ **Stopped by its owner** (`chi sessions stop`, the web's Stop: the stop marker,
111
+ `WorkerPresence#stop_marked?`) comes first, in both modes: a skip ("the session is
112
+ stopped; only its owner's message starts it again"), never a restart. A stop that
113
+ lands between the check and a same-mode firing is the same skip: `deliver_turn`
114
+ refuses a schedule's wake of a stopped session (a schedule is no person,
115
+ `ClientId.wake_kind`).
116
+
106
117
  **No live worker** (the usual case for a weekly schedule): the files say what can
107
118
  be known — the saved status is not `running` (and not inside the starting grace),
108
119
  `input/` is empty, no step-limit question is open, and, for chain mode, no worker
@@ -150,9 +161,20 @@ are the refusals that mean "not this moment": `ArchiveRefused` with `busy`, `que
150
161
  or `offer`, or `busy_child`/`queued_child`/`offer_child` (a chain's own running
151
162
  delegate refuses the archive, since `archivable!` walks the whole descendant tree),
152
163
  `SessionContinue::Refused(:continued)` (a human continued it while we were
153
- resolving) and `:open_children`.
154
-
155
- Anything else is a **failure** (`failures += 1`): a gone or archived target,
164
+ resolving) and `:open_children`. So is an archived target that a continue is still
165
+ making the next link of (`being continued as 7b2d41aa; retry at the next tick`): a
166
+ person's `chi send --new --continues` or web `continue →` archives the link before
167
+ its successor is saved, and a tick in that moment sees an archived end
168
+ (`ContinueIntent.in_flight`: the intent written, its lock held). It is checked before
169
+ the busy check, in both modes, and again by a same-mode firing's own look at the
170
+ files; the next tick's walk reaches the new link. A continue that ended between the
171
+ tick's listing and that look (its successor saved, its intent gone) is no failure
172
+ either: the firing walks again on a fresh listing, checks the new link as the tick
173
+ would, and queues its turn there. A stale intent (no continue holds
174
+ its lock: a crash, repaired by the next continue or list) is not in flight, so that
175
+ target still fails `archived`.
176
+
177
+ Anything else is a **failure** (`failures += 1`): a gone or archived target (an archived end of the chain: you retired it, and a schedule never brings it back),
156
178
  `SessionContinue::Refused(:folder_gone)`, `SessionManager::DeleteRefused`,
157
179
  `ModelProfile::MissingModel`, `OwnedByTUI`, `Session::NotFound`, and anything a
158
180
  spawn throws (`Errno::ENOSPC` included — `run_locked` re-raises it after undoing
data/docs/sessions.md CHANGED
@@ -23,17 +23,19 @@ Sessions are plain files — no DB. Each session is `~/.local/state/samagotchi/s
23
23
 
24
24
  A session is deleted if **expired by age OR overflow by count** (unless `keep_status` or the live-owner guard: a session a worker or `chi` still has open is never pruned). A session's `status` is its turn state (`idle`/`running`), not whether a worker is alive. Orphan dirs without a `*.json` are never deleted, except skeleton-only ones (see *Empty sessions*). Deletion removes its `*.json` and sidecar dir under the deleting owner lock, along with its plugin state, attached context, participant grants, System 1 runs and context-candidate records. Explicit delete and retention use the same cleanup path. Set both `DAYS=0` and `MAX=0` to retain forever.
25
25
 
26
- **Worker idle exit:** a background worker (plain `chi`, Web UI sessions) exits after `SAMAGOTCHI_SESSION_IDLE_EXIT_MINUTES` (`session.idle_exit_minutes`, default `30`, `0`=never) with no turn running or queued, no client on its stream (an open web tab or attached terminal keeps it), no reminder registered, no background task it watches for a [finish wake](internals/background-tasks.md#finish-wake) still running or waiting for its wake turn (with `session.task_wakes: wake`; not one whose turn you stopped) and no continue offer (the step-limit question) waiting for an answer. It removes `bridge.json` and frees `owner.lock`; the next prompt or `--attach` wakes a new worker (`WorkerIdleExit`, `WorkerBoot.run_session_loop`). As its Bridge stops, the worker marks the lock leaving (`OwnerLock#mark_leaving`: `leaving_at`, and `leave_wait`, its `recap.timeout`), since it keeps the lock while it writes the recap on leave: an `--attach` or `--resume` meanwhile (here, or a remote one through chi web's wake) prints `(waiting for the session to finish its recap…)` (`LaunchMode::RECAP_WAIT`) and waits for the release, up to that budget plus `OwnerLock::LEAVE_MARGIN` (5 s), before starting the new worker (`OwnerLock.await_release`). A lock held by a worker that isn't leaving (a live one, a stuck one) is left as before. A client can also ask the worker to exit right away (Bridge `POST /session/:id/exit`; `/exit` in an attached terminal does, `/detach` doesn't): the same rules apply without the timeout (even with `0`), and the asker's own stream doesn't count. The reply names what keeps it up (for background tasks, which ones and how to stop them). When every hold is one the user can stop — reminders, a watched task still running, a delegate with a live worker — the 409 also carries `holds: [{kind:, items: [{id:, label:, detail:}]}]` (a reminder's detail is its schedule, `every 20m`/`every 1h`, `, due now` when it is already due), and an attached terminal asks what to do with them; its "stop them and exit" posts `{"stop": "all"}`, which clears the reminders, stops those tasks (`TaskRuntime.stop_task`, as `task_stop`) and stops those children (`SessionManager.stop_session`) before leaving, re-checking first that nothing the user can't stop appeared meanwhile (`HoldStop`). A delegate counts only for that ask: it never holds the idle exit, and an exit that deletes or archives the session does not ask about it. The session's status stays as it was, not `stopped`. With `"restart": true` (a worker whose sidecar lists the `restart` feature) the worker hands the session to a new worker on the newest chi installed: it leaves, then starts its successor once its lock is free, keeping even an empty session and writing no recap. Clients' streams don't hold a restart (a web tab and an attached terminal reconnect to the new worker); what would be lost does: a turn running or queued, a continue offer, a question or approval waiting, a `/btw` (or another anytime command) still running, a delegate's approval relay open or settled in the last 10 minutes, and background tasks this conversation started that still run (`WorkerIdleExit#hold_for_restart`; 409 `held` with `reason`). Reminders go along: as it leaves, the worker writes them to `<id>/reminders.json` (0600: `session_id`, `written_at`, and each reminder's id, name, description, interval and next fire as wall-clock time; `ReminderCarry`), and its successor reads and deletes the file as it starts, before its idle scheduler runs. A restored reminder keeps its id and schedule; one that came due meanwhile fires once at once, and one further ahead than its interval (a clock that jumped) is due one interval from now. The file counts only for the same session within 2 minutes of `written_at`, and not once the session is stopped: otherwise it is deleted unread (log `reminders_carry_dropped`, at warn unless the session was stopped). A stop that lands while the worker leaves for a restart wins: the worker writes no file, and no successor starts (`WorkerBoot.run_session_loop`, log `restart_dropped`). So does one that lands as it leaves any other way (an idle exit, `/exit`, a signal) with input queued or delegate reports waiting: no new worker un-stops it (log `respawn_dropped`), and what waits stays for the next start. A send after the stop still un-stops it, as a send always does: one that reaches a leaving worker clears the stop, so the leave's new worker runs it (log `send_unstopped_leaving`); an archive deletes the file of each session it archives. Once an exit or restart is taken (claimed before a stop-all stops anything), the first one decides how the worker leaves: a later request of the same kind is answered as that exit, one of another kind (a stop-all from another terminal after a restart, chi web's "Restart workers" after a `/exit`) gets 409 `held` with `reason` `leaving_exit`, `leaving_delete` or `leaving_restart`, and a restart says it was refused rather than "restarted". A write that fails keeps the worker up with its reminders (log `reminders_carry_failed`), and the caller reports no new worker. A reminder already due when the restart is asked runs its turn first, so the restart's wait (10 s) may report no new worker yet though the hand-off follows. A worker from before this still refuses a restart for its reminders (409 `reminders`). Only an asked restart carries them: the fallback's TERM (a worker that can't be asked, below), a stop, an idle exit (which reminders hold anyway) and a crash drop them as before. What lives only in the worker's memory goes: the event history a late client replays, the kept `/btw` answers, a plugin's in-memory state.
26
+ **Worker idle exit:** a background worker (plain `chi`, Web UI sessions) exits after `SAMAGOTCHI_SESSION_IDLE_EXIT_MINUTES` (`session.idle_exit_minutes`, default `30`, `0`=never) with no turn running or queued, no client on its stream (an open web tab or attached terminal keeps it), no reminder registered, no background task it watches for a [finish wake](internals/background-tasks.md#finish-wake) still running or waiting for its wake turn (with `session.task_wakes: wake`; not one whose turn you stopped) and no continue offer (the step-limit question) waiting for an answer. It removes `bridge.json` and frees `owner.lock`; the next prompt or `--attach` wakes a new worker (`WorkerIdleExit`, `WorkerBoot.run_session_loop`). As its Bridge stops, the worker marks the lock leaving (`OwnerLock#mark_leaving`: `leaving_at`, and `leave_wait`, its `recap.timeout`), since it keeps the lock while it writes the recap on leave: an `--attach` or `--resume` meanwhile (here, or a remote one through chi web's wake) prints `(waiting for the session to finish its recap…)` (`LaunchMode::RECAP_WAIT`) and waits for the release, up to that budget plus `OwnerLock::LEAVE_MARGIN` (5 s), before starting the new worker (`OwnerLock.await_release`). A lock held by a worker that isn't leaving (a live one, a stuck one) is left as before. A client can also ask the worker to exit right away (Bridge `POST /session/:id/exit`; `/exit` in an attached terminal does, `/detach` doesn't): the same rules apply without the timeout (even with `0`), and the asker's own stream doesn't count. The reply names what keeps it up (for background tasks, which ones and how to stop them). When every hold is one the user can stop — reminders, a watched task still running, a delegate with a live worker — the 409 also carries `holds: [{kind:, items: [{id:, label:, detail:}]}]` (a reminder's detail is its schedule, `every 20m`/`every 1h`, `, due now` when it is already due), and an attached terminal asks what to do with them; its "stop them and exit" posts `{"stop": "all"}`, which clears the reminders, stops those tasks (`TaskRuntime.stop_task`, as `task_stop`) and stops those children (`SessionManager.stop_session`) before leaving, re-checking first that nothing the user can't stop appeared meanwhile (`HoldStop`). A delegate counts only for that ask: it never holds the idle exit, and an exit that deletes or archives the session does not ask about it. The session's status stays as it was, not `stopped`. With `"restart": true` (a worker whose sidecar lists the `restart` feature) the worker hands the session to a new worker on the newest chi installed: it leaves, then starts its successor once its lock is free, keeping even an empty session and writing no recap. Clients' streams don't hold a restart (a web tab and an attached terminal reconnect to the new worker); what would be lost does: a turn running or queued, a continue offer, a question or approval waiting, a `/btw` (or another anytime command) still running, a delegate's approval relay open or settled in the last 10 minutes, and background tasks this conversation started that still run (`WorkerIdleExit#hold_for_restart`; 409 `held` with `reason`). Reminders go along: as it leaves, the worker writes them to `<id>/reminders.json` (0600: `session_id`, `written_at`, and each reminder's id, name, description, interval and next fire as wall-clock time; `ReminderCarry`), and its successor reads and deletes the file as it starts, before its idle scheduler runs. A restored reminder keeps its id and schedule; one that came due meanwhile fires once at once, and one further ahead than its interval (a clock that jumped) is due one interval from now. The file counts only for the same session within 2 minutes of `written_at`, and not once the session is stopped: otherwise it is deleted unread (log `reminders_carry_dropped`, at warn unless the session was stopped). A stop that lands while the worker leaves for a restart wins: the worker writes no file, and no successor starts (`WorkerBoot.run_session_loop`, log `restart_dropped`). So does one that lands as it leaves any other way (an idle exit, `/exit`, a signal) with input queued or delegate reports waiting: no new worker un-stops it (log `respawn_dropped`), and what waits stays for the next start. A person's send after the stop (chi send, a web tab, a terminal) still un-stops it, as a person's send always does (see *Who may wake a session* below): one that reaches a leaving worker clears the stop, so the leave's new worker runs it (log `send_unstopped_leaving`); an archive deletes the file of each session it archives. Once an exit or restart is taken (claimed before a stop-all stops anything), the first one decides how the worker leaves: a later request of the same kind is answered as that exit, one of another kind (a stop-all from another terminal after a restart, chi web's "Restart workers" after a `/exit`) gets 409 `held` with `reason` `leaving_exit`, `leaving_delete` or `leaving_restart`, and a restart says it was refused rather than "restarted". A write that fails keeps the worker up with its reminders (log `reminders_carry_failed`), and the caller reports no new worker. A reminder already due when the restart is asked runs its turn first, so the restart's wait (10 s) may report no new worker yet though the hand-off follows. A worker from before this still refuses a restart for its reminders (409 `reminders`). Only an asked restart carries them: the fallback's TERM (a worker that can't be asked, below), a stop, an idle exit (which reminders hold anyway) and a crash drop them as before. What lives only in the worker's memory goes: the event history a late client replays, the kept `/btw` answers, a plugin's in-memory state.
27
27
 
28
- **Empty sessions:** a session nothing happened in is deleted when it is left, so `chi` → `/exit` leaves no trace. Empty means: no messages, no turn tried (a failed turn leaves a `last_prompt` and keeps it), no memory used, no pending question, nothing in `input/`, `notes/` or `images/`, nothing in its dir beyond the worker's skeleton, mode `assist`, and the default model. A session on another model (`/model`, `--model`) counts as prepared and stays (`SessionManager.discardable?`). The worker checks as it idle-exits or leaves on a client's request and deletes it once its lock is free, checking again first. The attached `/exit` then says `Detached; the session is empty: it will be discarded if nothing arrives before its worker stops.` (a note or prompt landing first keeps it). The retention sweep catches those killed first: empty sessions over an hour old with no live owner, whatever `DAYS`/`MAX`, and skeleton-only dirs with no `*.json`. `session.keep_empty: true` (env `SAMAGOTCHI_SESSION_KEEP_EMPTY`) turns all of it off.
28
+ **Empty sessions:** a session nothing happened in is deleted when it is left, so `chi` → `/exit` leaves no trace. Empty means: no messages, no turn tried (a failed turn leaves a `last_prompt` and keeps it), no memory used, no pending question, nothing in `input/`, `notes/` or `images/`, nothing in its dir beyond the worker's skeleton, mode `assist`, and the default model. A session on another model (`/model`, `--model`) counts as prepared and stays (`SessionManager.discardable?`). The worker checks as it idle-exits or leaves on a client's request and deletes it once its lock is free, checking again first. The attached `/exit` then says `Detached; the session is empty: it will be discarded if nothing arrives before its worker stops.` (a note or prompt landing first keeps it). The retention sweep catches those killed first: empty sessions over an hour old with no live owner, whatever `DAYS`/`MAX`, and skeleton-only dirs with no `*.json` (removed as a delete removes, every session store, under the session's lock: a worker or a start that took the session since the check keeps it, and so does one whose file or content was written meanwhile, read again under that lock). `session.keep_empty: true` (env `SAMAGOTCHI_SESSION_KEEP_EMPTY`) turns all of it off.
29
29
 
30
30
  **Participants:** a session its owner invited participants to review (`chi share`, see [CLI: Participants](cli.md#participants)) has two more files in its dir, neither in the session JSON: `participants.json` (0600), who is or was invited (`{participants: [{id, kind, name, role, added_at, expires_at, removed_at}]}`, never a token), which chi web and `chi share` write and the worker reads (`Participants.read`); and `participants.jsonl` (0600, append-only), the audit trail (grants issued, revoked and expired, each new peer, refused routes). A session nobody was invited to has neither. A continue, a fork or a delegate starts with no participants. Archiving or deleting the session revokes its links. See [internals/participants.md](internals/participants.md).
31
31
 
32
32
  **Always attached:** every interactive `chi` (plain, `-p`, `--resume ID`, `--attach ID`, `chi scratch`) runs its session in a background worker and attaches to it; there is no setting for it. The worker runs in the session's `working_directory`, so `!commands` and tools see the directory the session was started in. Only `chi -p TEXT --non-interactive` runs its one turn in this process; while it does, the session can't be attached ("in use by a one-turn chi --non-interactive run or an older chi's terminal"). See [CLI: Sharing a session](cli.md#sharing-a-session).
33
33
 
34
+ **Who may wake a session:** every turn delivery names its sender (`SessionManager.deliver_turn` requires `client_id`), and the sender's kind picks what it may do to the worker (`ClientId.wake_kind`, `SessionInbox::WakePolicy.for_sender`). A person — `chi send`, a web tab, an attached terminal — starts an idle session, un-stops a stopped one and brings back an archived link. A schedule's firing, a plugin's `ctx.sessions.send`, a `delegate` follow-up, a participant's turn and any sender chi doesn't name start an idle session only: a session its owner stopped or archived refuses them (409 `session_stopped`, "the session is stopped; only its owner's message starts it again", or `session_archived`, "…brings it back"), nothing written. A schedule counts that as a skip (and skips a stopped session at its check, [scheduling.md](scheduling.md)); `delegate` says it as `Error: session <id8> refused: …`; a plugin gets `Error`. A turn already handed to a live worker is that worker's, as before. chi web's owner turn and command routes name a body that carries no `client_id` as `web:unnamed` (a web tab's rights).
35
+
34
36
  **Which chi a worker runs:** a new or woken worker runs the newest chi installed for this Ruby (`gem 'samagotchi', '>= 0.a'`, prereleases count), whoever starts it: a `chi web` or terminal still on an older chi starts it on the newest one, so a stale process doesn't spread old code. A worker already running keeps its version until it is restarted. Should the newest install fail to load, the worker runs the starter's own version and logs `boot_fallback` (its stdio is `/dev/null`). Under `bundle exec` the worker drops Bundler's env first, so it activates the newest gem too. Two consequences: a wrapper pin (`chi _0.17.0_ web`) pins only that process, not the workers it starts; and a source checkout (`bin/chi` in a worktree, `bundle exec`) starts its workers on its own `lib/`, but a session it made that is later woken by an installed chi (`chi web`, `chi send`) runs the installed code. The names an older starter hands a newer worker (the boot line, its env keys, `input/` files, the session JSON fields and the Bridge routes sessions use on each other) are pinned in `spec/worker_contract_spec.rb`. A chi newer than 0.130.0 keeps the top-level keys it doesn't know (a newer chi's fields) when it saves a session, after its own, and doesn't act on them; `written_by` names the chi that saved the file last, and a worker woken on a file a newer chi saved logs `newer_writer`. chi 0.130.0 and older drop those keys: a session a newer chi made loses its newer fields when an older chi wakes or saves it (for example `chi --attach` from a project whose Ruby has an older chi). Keep the chi in every Ruby you run it from newer than 0.130.0.
35
37
 
36
- A new session field is one `Session::FIELDS` row, plus a `SessionSetup` member when a fork and a continue carry it (`SessionSetup.of` and `Session.new_session` go by its members). The rule in `FIELDS`' comment: only top-level keys are kept (a new sub-key of `review`, `toolkit` or another value object is still dropped by an older chi), and an older chi keeps a key without honouring it, so a new field must be safe to come back unchanged after an older chi ran turns on the session.
38
+ A new session field is one `Session::FIELDS` row, plus a `SessionSetup` member when a fork and a continue carry it (`SessionSetup.of` and `Session.new_session` go by its members): a `SessionSetup.from_request` keyword too when a new-session request can give it, and a cell per entrypoint in `spec/session_setup_entrypoints_spec.rb` (it fails until each has one). The rule in `FIELDS`' comment: only top-level keys are kept (a new sub-key of `review`, `toolkit` or another value object is still dropped by an older chi), and an older chi keeps a key without honouring it, so a new field must be safe to come back unchanged after an older chi ran turns on the session.
37
39
 
38
40
  **A worker outlives whoever started it:** a spawned worker leaves its spawner's process tree (it is forked again, in a session of its own, and reparented to init), so closing the terminal of a `chi web`, or a tool tearing down a background `chi send --wait` and its children, no longer takes the worker and its turn with it.
39
41
 
@@ -43,7 +45,7 @@ A new session field is one `Session::FIELDS` row, plus a `SessionSetup` member w
43
45
 
44
46
  **Deleting a session:** `chi sessions delete ID...`, `/exit --delete` in a terminal and the Web UI's delete all go through `SessionManager.delete_session`: it resolves a unique prefix, removes `<id>.json` and the whole `<id>/` dir, and returns what it removed. A session a one-turn `chi --non-interactive` run has (`owner.lock` kind `tui`) is always refused. One a worker runs is refused unless the caller asks to stop it: then it stops the worker as `chi sessions stop` does and deletes once `owner.lock` is free (`--force` on the CLI, 10 s; the web page always, 2 s; `/exit --delete` after the worker agreed to exit, 10 s). A worker that outlives the wait leaves the session in place. A session whose worker is being started (the `<id>/starting` marker) is refused or stopped the same way, and the files go while the delete holds `owner.lock`, so a worker can't take the session in the middle; a worker that still had it loaded doesn't write it back. The web's route is `DELETE /api/sessions/:id?force=true` (the page sends `force`; without it a live worker's session is 409 `worker_running`, as the CLI without `--force`; 200 `{status: "deleted", session_id, stopped}`; 409 `owned_by_tui` or `still_stopping`; 404).
45
47
 
46
- <a id="archiving-a-session"></a>**Archiving a session:** `chi sessions archive ID...`, `/archive` in a terminal and the Web UI's `archive` go through `SessionManager.archive_session`: it writes `<id>/archived` (`{"archived_at": …}`; not a session.json field, which every save rewrites) for the session and its delegated children. `Session.list` leaves archived sessions out unless `include_archived:`, and everything built on it follows: `chi sessions list` (`--archived` shows them, `[archived]`), the summaries (`--live`, json/tsv, the desktop panel, the agent's `list_sessions`) and the retention prune, which neither deletes nor counts them against `max_count`. `children_of` (max_children, `delegate_result`) still sees them, and `--resume`/`--attach ID`, `chi send`/`chi note ID` reach them as before. Refused: a turn running in the session or in one of its children (naming the child; 409 `busy` on the web), a prompt queued in `input/` (it would run on the next resume) or a live worker's step-limit question still open, in it or a child (409 `busy` too), a one-turn `chi --non-interactive` run owning it (`owned_by_tui`), a `chi scratch` session (`scratch`). A live idle worker is stopped first, and the marker is written even if it is still shutting down. Input a human typed brings a session back (`{"unarchived_at": …}`): a prompt from the web, an attached terminal or `chi send` (origin `web:*`, `tui:*`, `cli:send`, none), steering merged into a running turn, a `/continue` answer or a question answered (the step-limit question too); a delegate's follow-up, a plugin's turn, a reminder, the idle recap, a note and just opening it don't. A child's input brings only the child back. The retention sweep ages an unarchived session from when it was unarchived, so unarchiving an old session doesn't let the next sweep take it. `/archive` leaves the session first, as `/exit` does, then archives it: in an attached terminal the worker is asked to exit (one that stays up for another UI is stopped by the archive; a running turn, a queued prompt or an open step-limit question refuses it), and an empty session is discarded instead; `chi scratch` refuses it. Typed while a turn runs, `/archive` waits for the turn's end (an attached terminal for the commands queued behind it too) and then archives. `chi sessions unarchive ID...` and the web's `unarchive` bring back the whole family. Web routes: `POST /api/sessions/:id/archive` (200 `{status, session_id, archived, stopped, discarded}`, ids) and `POST /api/sessions/:id/unarchive` (200 `{status, session_id, unarchived}`). The session hub and `GET /api/sessions` keep archived sessions, `archived: true` in their summaries: the page leaves them out of the strip, its count and the list at render, and the `archived` toggle beside the all-sessions search shows them, dimmed with an `archived` badge. The info bar marks a session whose live worker runs an older chi than the newest installed (`worker_version` in its summary): `chi 0.18.1 · Restart`, which asks to confirm and calls `POST /api/sessions/:id/restart` (a refusal's reason shows in a toast); a worker from before restarts shows `chi sessions stop ID` instead. The info bar reads `continue → · archive · stop · delete` (`unarchive` on an archived one; no `continue →` on a link continued already, see *Session chains*; `continue →` is a plain button like `archive`, in the accent on an archived session, where it is the thing to do); archiving the open session stays on it, with an Undo toast.
48
+ <a id="archiving-a-session"></a>**Archiving a session:** `chi sessions archive ID...`, `/archive` in a terminal and the Web UI's `archive` go through `SessionManager.archive_session`: it writes `<id>/archived` (`{"archived_at": …}`; not a session.json field, which every save rewrites) for the session and its delegated children. `Session.list` leaves archived sessions out unless `include_archived:`, and everything built on it follows: `chi sessions list` (`--archived` shows them, `[archived]`), the summaries (`--live`, json/tsv, the desktop panel, the agent's `list_sessions`) and the retention prune, which neither deletes nor counts them against `max_count`. `children_of` (max_children, `delegate_result`) still sees them, and `--resume`/`--attach ID`, `chi send`/`chi note ID` reach them as before, except that `chi send` and `chi note` to a link that was continued go to its chain's newest link (*Session chains*). Refused: a turn running in the session or in one of its children (naming the child; 409 `busy` on the web), a prompt queued in `input/` (it would run on the next resume) or a live worker's step-limit question still open, in it or a child (409 `busy` too), a one-turn `chi --non-interactive` run owning it (`owned_by_tui`), a `chi scratch` session (`scratch`). A live idle worker is stopped first, and the marker is written even if it is still shutting down. Input a human typed brings a session back (`{"unarchived_at": …}`): a prompt from the web, an attached terminal or `chi send` (origin `web:*`, `tui:*`, `cli:send`, none), steering merged into a running turn, a `/continue` answer or a question answered (the step-limit question too); a delegate's follow-up, a plugin's turn, a reminder, the idle recap, a note and just opening it don't. A child's input brings only the child back. The retention sweep ages an unarchived session from when it was unarchived, so unarchiving an old session doesn't let the next sweep take it. `/archive` leaves the session first, as `/exit` does, then archives it: in an attached terminal the worker is asked to exit (one that stays up for another UI is stopped by the archive; a running turn, a queued prompt or an open step-limit question refuses it), and an empty session is discarded instead; `chi scratch` refuses it. Typed while a turn runs, `/archive` waits for the turn's end (an attached terminal for the commands queued behind it too) and then archives. `chi sessions unarchive ID...` and the web's `unarchive` bring back the whole family. Web routes: `POST /api/sessions/:id/archive` (200 `{status, session_id, archived, stopped, discarded}`, ids) and `POST /api/sessions/:id/unarchive` (200 `{status, session_id, unarchived}`). The session hub and `GET /api/sessions` keep archived sessions, `archived: true` in their summaries: the page leaves them out of the strip, its count and the list at render, and the `archived` toggle beside the all-sessions search shows them, dimmed with an `archived` badge. The info bar marks a session whose live worker runs an older chi than the newest installed (`worker_version` in its summary): `chi 0.18.1 · Restart`, which asks to confirm and calls `POST /api/sessions/:id/restart` (a refusal's reason shows in a toast); a worker from before restarts shows `chi sessions stop ID` instead. The info bar reads `continue → · archive · stop · delete` (`unarchive` on an archived one; no `continue →` on a link continued already, see *Session chains*; `continue →` is a plain button like `archive`, in the accent on an archived session, where it is the thing to do); archiving the open session stays on it, with an Undo toast.
47
49
 
48
50
  **System 1's saved runs** last as long as sessions: the sweep ages them by day file, and deleting a session purges its runs ([system-one.md](system-one.md)).
49
51
 
@@ -303,6 +305,7 @@ pbpaste | chi send 3fa2 # the clipboard is the messa
303
305
  - Fire and forget: it returns once the message is queued and never prints the answer; that shows in whatever is attached. A guardrail "ask" waits for a UI to answer it, so with nothing attached the turn stalls there until one attaches (`chi --attach ID`).
304
306
  - `--image PATH` (repeatable, up to 20) sends images with the message, as the web composer's chips do. Each file is read once before anything is sent (bmp, tiff and heic converted to png, large ones downscaled, as for `@path`); a missing file or one that isn't an image stops the send (exit 1; with `--wait --format json`, an `error` line) and nothing is sent; more than 20 is a usage error (exit 2). Each session gets its own copy in `<session>/images/`. Text is still required (`-m` or stdin; context alone counts), also with `--wait`. The session's model must see images: one known not to (the host's model list says text-only, `vision: false` in `models:` or `hosts:`, a native llama.cpp without a vision model) is refused before anything is sent, with the reason (`<id> refused: gemma can't take images (…); send text only or switch the model (/model)`); the other sessions of the same send still get it, and the exit is 1. With `--new` nothing is started. When chi can't tell (a native host whose `/props` doesn't answer, a list that doesn't say), the message is sent as before and a text-only model fails the turn in the session. A running turn doesn't take images mid-turn: the message runs as the next turn, and the line says `(runs after the current turn)`. With `--new` the session starts idle with the message as its preview, then the message goes in as its first turn once its worker is up (`<id> started with 1 image`); if the worker doesn't come up in 5 s the session is kept, with its id on the `failed:` line.
305
307
  - A session command runs as the command, as typed in a terminal: `chi send -m "/model qwen" 3fa2` switches the model (`sent as a session command`), and the model never sees the line. What counts is what the session's worker knows (the built-ins, `!cmd`, its bundles' commands); an unknown `/word` (`/usr/bin/env is missing`) goes in as a message. A UI-only command (`/stats`, `/exit`, `/recap`, …) is refused instead: the worker doesn't run it, so the line would reach the model as a prompt (`<id> refused: /stats is a terminal and web command; use chi sessions stats <id8>`; exit 1, and nothing is sent). With `--new` a line starting with `/` or `!` starts the session idle and goes to its worker once it is up, which decides. With `--wait` a command has no reply to wait for: exit 0 at once, `<id> sent as a session command: no reply to wait for …` on stderr (`{"status":"command",…,"detail":…}` with `--format json`); its output shows where the session is open.
308
+ - A session that was **continued** (archived, with a later link): the message goes to its chain's newest link, as a note does (*Context notes*), and the old link stays archived. The line names both, in `chi note`'s wording: `3f9a1c2e → 7b2d41aa (continued) sent`. Every id is resolved once, before anything is sent (`SessionAccess#head`, `SessionInbox::Head`'s walk for the `send` row), so the parent-answers check, images, a session command, the UI-only refusal and `--wait` all act on that newest link, and `chi send OLD NEW` sends once. `--wait` waits there: its `--format json` `session_id` is the newest link's, and `asked` the id given (only when they differ). `--wait` without a message follows too, but `--wait --turn T` of the old link (a turn from before the continue) waits on the old one. A link archived and never continued is still brought back by a send. A link being continued right now (its intent written, its new link not saved yet: `SessionContinue`) is asked again for up to 10 s; still not there, it is refused and nothing is written: `3f9a1c2e refused: being continued as 7b2d41aa; send again in a moment`. A continue that ends or starts after that resolve still never gets the old link: chi send's delivery says it follows (`deliver_turn`'s `follow:`, `follow: true` on chi web's turn route for `chi --remote`), and an archived link with a saved successor, or one a continue holds the lock of, refuses it (409 `link_continued`, nothing written; the check and the input go in under a shared hold of that lock, so no continue starts between them); chi send resolves again and sends to the new link (taking back the `--image` copies it made in the old one, on this machine; `chi send OLD NEW` still sends once), for up to 10 s, then `refused: being continued; send again in a moment` (an older chi web ignores the field and sends as before). A chain's first link's id is a stable address for the whole chain. What stays on the id it names: the web composer (typing on an archived link's page brings that link back), a participant's turn (a grant is for one session), `delegate(session:)`, a plugin's turn and a schedule (its own rule, *Schedules*).
306
309
  - One line per session: `sent`, `sent as a session command`, `sent with 2 images`, `sent (goes in at the running turn's next step)`, with `--cut` `sent (cut in now)`, `sent (cuts in once the thinking passes 20 s)` or `sent (cutting is off; goes in at the next step)`, with `--queue` `sent (queued: runs after the current turn)`, `sent (the running turn had ended: it runs now)` or `sent (nothing running: it runs now)`, `sent (started its worker)`, `refused: …` or `failed: …`. Exit 0 when all were sent, 1 when any was refused, failed or not found, 2 for a usage error. There is no `--all`.
307
310
 
308
311
  The Automator action above works for messages too: swap its last line for `pbpaste | "$chi" send -m "what do you make of this?" $(print -r -- "$picked" | cut -f1)`.
@@ -357,12 +360,12 @@ A session can **continue** an earlier one: "the next run of the same routine" (a
357
360
  - **The recap first:** a previous link with a live worker is asked for a recap (the Bridge's `POST /recap`) and given up to 30 s to write it; one with none wrote its recap when its worker left.
358
361
  - **The previous link is archived** before the new one starts, by the archive's own rules (see *Archiving a session*): a turn running, a prompt queued or the step-limit question refuse it, a live idle worker is stopped, a session a one-turn `chi --non-interactive` run has is refused. Its finished delegates are archived with it, as any archive does. Before archiving, the continue writes `<previous>/continue.json` with the reserved successor id. Session lists and the next continue repair an interrupted operation under `continue.lock`: if that successor's session file was not saved, they unarchive the previous link and remove the intent; if it was saved as its successor, they clear the intent and keep the archive.
359
362
  - **Its open delegates move to the new link** instead: each direct delegate that is running, waiting for an answer, has a live worker or a reply its parent wasn't given, or has such a delegate below it (checked again after the recap wait, so one delegated meanwhile moves too). It moves with its own delegates, stays unarchived, and from then on is the new link's: its card folds under the new link, its reports ring the new link (an idle one runs a wake turn for them, as for its own delegates), `delegate_result` and the `⑂` chip count it there, and what its parent was already told (`delegates.json`) and any report still waiting come along, so nothing is reported twice. A moved delegate gets a context note from `session chain`, `Your parent session is now 4b7e9a01 (…), the next link of its session chain: …`, as its system prompt keeps naming the parent it started with. The move writes `<child>/parent.json` (`{parent_id, from, at}`) beside the child's session file, never the file itself, so a live child worker saving its own copy changes nothing; every reader applies it (a later move overwrites it; it is never removed). A continue is **refused for an open delegate that can't move** (`SessionContinue::Refused`, naming it): one whose live worker runs an older chi (`older chi worker 0.46.1; restart it`: `chi sessions restart <id>`, or stop it) or that a one-turn `chi --non-interactive` run has (`in use by a one-turn chi --non-interactive run or an older chi's terminal; let it finish`). An older `chi web` or CLI still running shows a moved delegate under the archived link until it is restarted.
360
- - **If the continue fails part-way:** a new link that fails to start gives its moved delegates back before it is deleted (each gets a note saying so; its worker is stopped first, if one started, and a worker that won't stop is reported, the link left), with any report one of them rang it with meanwhile, and the notes it moved with any sent to it meanwhile (never the continue's own: the carry note, the attached-context note, the objectives' list): its session file goes first, so a note sent to the previous link from then on stays there, then the notes go back, then its folder goes, and a note an older chi writes into it after that is given back too (a note for a session with no file and no folder is refused, never a stray folder); the previous link, back in the lists, is woken for reports waiting. A continue that dies in the middle leaves a `move.json` in the new link's folder: the new link's next worker finishes that move (only the delegates it names, and without a second note to one already told) as it starts. Its `continue.json` intent remains in the previous link's folder too, so a later list can restore it if the successor was never saved. Until the new link's own worker holds it, a ring from a moved delegate doesn't start another (a `starting` marker in its folder, which that worker removes; a stale one, over 60 s old or from a process that is gone, is ignored). An open delegate below an archived delegate refuses the continue (`under archived …`): unarchive that one, or archive this one.
363
+ - **If the continue fails part-way:** what a continue carries (its delegates, attached context, objectives and notes, in that order) and how each is given back is one list, `SessionContinue::CARRY` (the per-session stores it leaves behind, and why, are `SessionContinue::NOT_CARRIED`). A new link that fails to start gives its moved delegates back before it is deleted (each gets a note saying so; its worker is stopped first, if one started, and a worker that won't stop is reported, the link left), with any report one of them rang it with meanwhile, and the notes it moved with any sent to it meanwhile (never the continue's own: the carry note, the attached-context note, the objectives' list): its session file goes first, so a note sent to the previous link from then on stays there, then the notes go back, then its folder goes, and a note an older chi writes into it after that is given back too (a note for a session with no file and no folder is refused, never a stray folder); the previous link, back in the lists, is woken for reports waiting. A continue that dies in the middle leaves a `move.json` in the new link's folder: the new link's next worker finishes that move (only the delegates it names, and without a second note to one already told) as it starts. Its `continue.json` intent remains in the previous link's folder too, so a later list can restore it if the successor was never saved. Until the new link's own worker holds it, a ring from a moved delegate doesn't start another (a `starting` marker in its folder, which that worker removes; a stale one, over 60 s old or from a process that is gone, is ignored). An open delegate below an archived delegate refuses the continue (`under archived …`): unarchive that one, or archive this one.
361
364
  - **Refused too:** a link that is continued already (naming the link that continues it; continue that one, or `last:<id>`), a previous link whose folder is gone, and one whose model's host can't run it when no default model is configured to fall back to. A refusal starts nothing and archives nothing; a new link that fails to start puts back what was archived. Every refusal that can be known up front (the archive's ones included) comes before the recap wait. One continue of a session runs at a time (a lock in its folder; other chains don't wait), so a double click finds the first one's link and is refused, while a `last:<id>` continue that waited follows the chain to its new end.
362
365
  - **Web:** `POST /api/sessions` takes `continues: "<id, prefix or last:id>"`, with `idle: true` (a new link waiting for its first message, previewed by the previous link's, or `preview`) or a `prompt`, and `model` (or `model_name`) for the new link's model, but not `dir`, `llm_context`, `thinking`, `settings`, `toolkit`, `tools`, `no_tools` or `parent_answers` (400 `invalid_continues`: the previous link's are taken). 201 is the new session's summary, `continues` set, with `moved`: the ids of the delegates that moved to it (`[]` for none), and `model_warning`: the default-model fallback's warning, then any about the model id, joined by `; ` (`null` for none), and `opener`: the previous link's first typed message, in full, when that link continues one itself (`null` otherwise: a chain's first link's first message is its task), and `moved_context`: `{moved: [names], stayed: [{name, why}]}`, the attached context it took (`why` `pushed` or `not movable`); 404 `not_found`; 400 `ambiguous_id` for a prefix of several sessions, `invalid_model` for a given model whose host config.yml doesn't have (or a fallback with no default model); 409 `continued` with `next_id` (the link that continues it already, which the page opens instead), `open_children` with `ids` (open delegates that can't move), `folder_gone`, `busy`, `scratch` or `owned_by_tui`. Every session summary carries `continues`.
363
366
  - **The page:** the info bar's `continue →` continues the open session (`continues: <id>, idle: true`; it reads `continuing…` through the recap wait) and opens the new link with an opener in the composer, not sent (a draft written in this session stays instead; one carried over from another session or the start page gives way to the opener, and the toast's **Restore draft** brings it back): the previous link's own first typed message when that link continues one (the 201's `opener`; a `!shell` line isn't taken), else `Continue where we left off.`. So whatever you sent on the last link comes back on the next one, and editing it once changes it for every later link; the previous link is archived, a toast says so (`Continued 3fa2c1d0 in 4b7e9a01; 3fa2c1d0 is archived; 1 open delegate moved`), and a moved delegate's card folds under the new link. When the previous link's model's host is gone the link starts on the default model and the toast carries the server's `model_warning` too, and then stays until closed. A fresh link (one with no turn yet, however it was made: `continue →`, `chi send --new --continues`, a reload) shows the model picker in its composer with the link's model, until its first turn starts (a failed or canceled first turn ends it too); a pick runs `/model <name>` in the link (a command bubble; the info bar follows) and changes neither the start page's remembered model nor its Recent list, and a Send right after it waits for the `/model` to be taken. A link a one-turn `chi --non-interactive` run has, or one continued already, shows none. A link continued already has no `continue →`: its `→` link goes to the next link (a stale page's continue answered 409 `continued` opens `next_id`). A continue refused for open delegates that can't move shows a toast that names each one (its preview and what the server says to do: `older chi worker 0.46.1; restart it`, `in use by a one-turn chi --non-interactive run or an older chi's terminal; let it finish`), each a link to its page; any other refusal shows the server's words. The info bar of a link carries `← 2026-10-08` (the previous link's day) and, on an earlier link, `2026-10-10 →`, each a link with its id, its full start (`2026-10-10 14:32`) and its preview in the tooltip; a neighbour that started on the open link's own day shows its time instead (`← 09:12`, `14:32 →`). A link made by `continue →` inherits the previous link's preview (and its title, if it has one) when it is created, so its card keeps its chain's title whatever opener it is sent, and its top bar and browser tab show its card's title. A link with a recap of its own reads its auto title, else its recap's first sentence, instead (a link without one reads its chain's name, and a first link's recap names its chain). A link whose title is the opener and nothing else (a `chi send --new --continues` link whose first message is `Continue where we left off.`) shows its chain's first link's title instead, on its card, in the popover and in its info bar's title line, display only (its messages and data keep the opener; its own title when the first link is gone). The lists fold a chain into the card of its latest listed link, whatever the earlier links' archived state (typing in an archived link brings it back, folded there still), their delegates with them: the card's `↩ #N` chip (`#N of M` when later links aren't listed; its tooltip `Session chain: link N of M`) opens a popover of the other links, newest first (`#N`, its date, with its time (`2026-10-17 14:32`) when another link of the chain started the same day, its own title when it differs from the card's (a link inherits its chain's, so mostly it doesn't), else its recap's first sentence, else its preview, `archived`), a click opens one; the chip shows a live dot or `waiting` for a link that has a worker or waits on the user, and a waiting link puts its chain's card first. All sessions folds nothing while a search is typed or the `archived` toggle is on: every link is a card of its own then, its chip `#N of M`, with its own delegates folded in, so a search finds an earlier link and its delegates.
364
367
  - **CLI:** `chi send --new --continues (ID|PREFIX|last:ID) [--model M] [-m TEXT]` (see *Starting a session*).
365
- - **Which link:** an id, a unique prefix, or `last:<id or prefix>`, the latest link of the chain that session is in. It walks the links that still exist: a deleted link in the middle (`chi sessions delete`, the retention sweep of an unarchived one) ends the walk before it, so `last:` of an earlier link then names that earlier link, and continuing it starts a second line beside the links after the gap; name a link after the gap instead. A trigger names the chain this way: `chi send` to an archived link would bring it back (a human's input), not continue the chain. That is the rule: a message (`chi send`, the web composer, `delegate(session:)`) goes to the link it names; a note goes to the chain's newest link (*Context notes*). A chain pruned by a schedule keeps its `anchor`: the kept window's oldest link still names a link that is gone, so the walk simply stops there; the page's chip counts from the surviving root (pruning renumbers the links) and its popover says `earlier links pruned` where the walk stops, rather than linking to a deleted session.
368
+ - **Which link:** an id, a unique prefix, or `last:<id or prefix>`, the latest link of the chain that session is in. It walks the links that still exist: a deleted link in the middle (`chi sessions delete`, the retention sweep of an unarchived one) ends the walk before it, so `last:` of an earlier link then names that earlier link, and continuing it starts a second line beside the links after the gap; name a link after the gap instead. A trigger names the chain this way: a person's message to an archived link that nobody continued brings it back (a human's input), it doesn't continue the chain; an unattended sender's is refused (*Who may wake a session*). That is the rule: `chi send` and a note go to the chain's newest link (*Sending a message*, *Context notes*); the web composer, a participant's turn and `delegate(session:)` go to the link they name. One walker answers every one of these (`SessionChain::Links`: one session listing, archive flags read once; the earliest created successor wins a fork a hand edit made, a loop ends where it would repeat), with two rules on it, not unified on purpose: `last:` and a schedule take the chain's **end** (`Links#latest`: a continue refuses a link continued already, and a schedule never un-archives a chain you retired), `chi send` and a note the **first link not archived** (`Links#first_live`: a person's input goes where the chain is live, and brings back an archived end). A chain pruned by a schedule keeps its `anchor`: the kept window's oldest link still names a link that is gone, so the walk simply stops there; the page's chip counts from the surviving root (pruning renumbers the links) and its popover says `earlier links pruned` where the walk stops, rather than linking to a deleted session.
366
369
 
367
370
  ## Schedules
368
371
 
data/docs/sub-agent.md CHANGED
@@ -233,6 +233,17 @@ answers from any local process.
233
233
  turn is the answer: its reply comes back (`answered`), or its end when it
234
234
  left no reply (`failed`, `canceled`, `limit`, …) — so a turn that finished
235
235
  in the gap between waits is reported, not waited for.
236
+ - A session you keep one id for (a coordinator, say) may be continued meanwhile
237
+ (`chi send --new --continues`, a chain schedule): `chi send` to that id goes
238
+ to its chain's newest link, and the old link stays archived. Keep the
239
+ chain's first id as its address. With `--format json`, `session_id` is the
240
+ link the message went to and `asked` the id you gave (only when they differ),
241
+ in every line after the id resolved (a refusal or an error too; a refused
242
+ send while the continue runs has `session_id` null and `asked`); the text
243
+ lines name both, `3f9a1c2e → 7b2d41aa (continued)`. `chi answer` and `--wait --turn T` take that `session_id` (a `--turn` of the
244
+ old link, from before the continue, waits on the old link). A send while the
245
+ continue itself runs waits a moment for the new link, else exits 1 with
246
+ `being continued as <id>; send again in a moment`.
236
247
  - An answer to a question that is no longer open (you answered it in the web
237
248
  first) isn't sent; `chi answer` says so and waits for what comes next. Its
238
249
  JSON then has `"answered_here": false` (absent when the answer went in), so
data/docs/testing.md CHANGED
@@ -148,9 +148,31 @@ override and a `note`. The Ruby side runs each row with every core command (a ne
148
148
 
149
149
  `spec/compat/readers_spec.rb` reads the newest recorded release before the
150
150
  current version (or the current corpus when it is the only one) through today's
151
- session, Bridge, CardStore, schedules and bundle-record readers. `rake
152
- release:bump[X.Y.Z]` writes `spec/compat/X.Y.Z/` using the current writers;
153
- commit those small samples with the release so the next version exercises N-1.
151
+ session, Bridge, CardStore, schedules and bundle-record readers, and the files
152
+ other chi versions write into a live session's folder: a queued input file, a
153
+ context note, a continue's intent (`continue.json`) and the stop marker (the
154
+ starting marker isn't recorded: a recorded one is always stale), a bundle's
155
+ install journal (`.bundles/compat/pending.json`), and the stores another chi
156
+ version shares: an interrupted continue's `move.json` (`ChildMove`), a
157
+ continue's `context/sessions/<id>/left.json`, stored approvals
158
+ (`guardrails/approvals.json`), and a participant's grant
159
+ (`web-grants/grants.json`) with its `participants.json` sidecar, and the chi
160
+ home (`home.json`). A corpus from
161
+ 0.164.0 or before has none of those and skips them; a later one must hold them.
162
+ Bridge wire payloads (`/state`, `/snapshot`, SSE frames) aren't recorded: a
163
+ sample needs a live Engine and Bridge at release time.
164
+ A second example reads a corpus the writer records now, so a writer change that
165
+ today's readers can't read goes red before the release. `rake
166
+ release:bump[X.Y.Z]` writes `spec/compat/X.Y.Z/` using the current writers
167
+ (`ReleaseTools.write_compat_corpus!`); commit those small samples with the
168
+ release so the next version exercises N-1.
169
+
170
+ Compat shims (code kept only for another chi version's data or protocol) are
171
+ registered in `Compat::SHIMS` (`lib/samagotchi/compat.rb`): an id, the release
172
+ that added it, `remove_after` (nil: the owner hasn't dated it) and its files,
173
+ each Ruby one naming it in a comment (`compat shim <id>`). `spec/compat_spec.rb`
174
+ fails once `Samagotchi::VERSION` passes a shim's `remove_after`, naming it:
175
+ remove the shim, or move its date with the owner's OK. A new shim gets a row.
154
176
 
155
177
  ## Levels
156
178
 
@@ -411,7 +433,9 @@ tools. Then come the other name matches (a spec named after several changed file
411
433
  `toolkit.rb`; then one beside the file, so `plugin/context.rb` picks `spec/samagotchi/plugin/*context*` before
412
434
  `spec/guardrails/context_spec.rb`), then the specs that name a method the change touches (the innermost `def` around a
413
435
  changed line, read with Prism; one `git grep` for up to 12 names; names under 4 characters, `initialize`, `to_s`,
414
- `call`… and `Object`'s or `Enumerable`'s methods skip), then the specs that name a changed file's class. The method tier
436
+ `call`… and `Object`'s or `Enumerable`'s methods skip; one that names the changed file's class too comes first), then
437
+ the specs that name a changed file's class, then the specs that name only the method (often another class's
438
+ `deliver`, which would crowd the class's own specs past the cap). The method tier
415
439
  needs Prism 1.0 or later: Ruby 3.4+ ships it, a 3.3 install has it only beside rubocop or minitest 6; below that it is
416
440
  skipped, which `--why` says. A method named in too many specs to list (a hub) gets a line under `--why` only. The default range is the merge-base with main (or origin/main) plus uncommitted and untracked files.
417
441
  The Ruby specs go to stdout; the node tests to run (`npm test` targets), "web changed: also run npm run e2e" (with `npm run lint` too when a frontend module changed) and a
@@ -38,6 +38,9 @@ module Samagotchi
38
38
  # Languages core draws itself: a bundle's renderer for one would be a
39
39
  # second drawer for the same block.
40
40
  RESERVED = [InlineWidgets::LANG].freeze
41
+ # The [bundle, problem] pairs .renderers has logged in this process.
42
+ WARNED = Set.new
43
+ WARNED_LOCK = Mutex.new
41
44
 
42
45
  module_function
43
46
 
@@ -97,25 +100,29 @@ module Samagotchi
97
100
  # owner's browser, so it is checked as a plugin's load and a provider's
98
101
  # script are; a --dev install's links are not.
99
102
  # @return [String, nil] nil when no such renderer loads such a file
100
- # @raise [Invalid] the file is gone or changed
103
+ # @raise [Invalid] the file is gone, has no recorded sha, or changed
101
104
  def script_path(bundle, file)
102
105
  return nil unless for_installed.any? { |renderer| renderer.bundle == bundle && renderer.files.include?(file) }
103
106
 
104
107
  provenance = MemoryBundle::Provenance.new(name: bundle)
105
- path = File.join(provenance.scripts_dir, file)
106
- recorded = provenance.record&.scripts&.fetch(file, nil)
107
- return path if File.file?(path) && MemoryBundle::Provenance.sha_matches?(path, recorded)
108
+ failure = provenance.script_failure(file, provenance.record&.scripts&.fetch(file, nil))
109
+ raise Invalid, failure if failure
108
110
 
109
- raise Invalid, "bundle #{bundle}'s scripts/#{file} differs from the installed one (reinstall the bundle)"
111
+ File.join(provenance.scripts_dir, file)
110
112
  end
111
113
 
112
- # Its parsed renderers; a list that doesn't parse is none (logged).
114
+ # Its parsed renderers; a kept list that doesn't parse is the record's
115
+ # mirror, else none. Logged once per bundle and problem: this runs on each
116
+ # list request and each renderer file fetch.
113
117
  def renderers(bundle, manifest)
114
- if (problem = manifest.problems["block_renderers"])
118
+ if (problem = manifest.problems["block_renderers"]) && WARNED_LOCK.synchronize { WARNED.add?([bundle, problem]) }
115
119
  Log.warn(:web, "block_renderers_unreadable", bundle: bundle, msg: problem)
116
120
  end
117
121
  manifest.block_renderers
118
122
  end
119
123
  private_class_method :renderers
124
+
125
+ # Forget what was logged (specs).
126
+ def reset_warnings! = WARNED_LOCK.synchronize { WARNED.clear }
120
127
  end
121
128
  end
@@ -271,7 +271,8 @@ module Samagotchi
271
271
  # A file from before the turn log: each entry's place by the count it was
272
272
  # saved with, killed turn included (nothing in it can say where a drifted
273
273
  # card was). New openings add to it. The next save keeps +base_since+.
274
- # Can go a retention period after the release that wrote version 2.
274
+ # Can go a retention period after the release that wrote version 2
275
+ # (compat shim cards_v1_seed: Compat::SHIMS).
275
276
  def seed_v1(data)
276
277
  killed_in_turn = data[:running] == true
277
278
  turns_done = data[:turns] + (killed_in_turn ? 1 : 0)
@@ -137,11 +137,11 @@ module Samagotchi
137
137
  end
138
138
 
139
139
  # The turn in progress (#current_turn's shape, symbol keys) as the live
140
- # events that would have drawn it, in order, as turn_events.js
141
- # snapshotEvents replays it for the web (spec/shared/turn_snapshot.json
142
- # pins both): a generation_started per generation part (a join during
143
- # a hold shows the step the model is on), a generation_chunk per
144
- # thinking or text part (a
140
+ # events that would have drawn it, in order, for the TUI and, through
141
+ # .join_events, the web (spec/shared/turn_snapshot.json pins both): a
142
+ # generation_started per generation part (a join during a hold shows
143
+ # the step the model is on), a generation_chunk per thinking or text
144
+ # part (a
145
145
  # generation_completed closes text before the next step's), a tool's
146
146
  # tool_call_started and, once finished, its tool_call_completed (with
147
147
  # the live activity: action, tool, params, status), a merged_input
@@ -207,9 +207,8 @@ module Samagotchi
207
207
  end
208
208
 
209
209
  # The page's unfold of a session view (chi web's show sends it as
210
- # `replay`; turn_events.js snapshotEvents was its JS twin): the turn in
211
- # progress as #replay_events has it, its turn_started with what the
212
- # page also reads (its wall time `at`, the run's `cut_after`, and every
210
+ # `replay`): the turn in progress as #replay_events has it, its
211
+ # turn_started with what the page also reads (its wall time `at`, the run's `cut_after`, and every
213
212
  # author key, a pair turn's participant_mode too), then a turn_enqueued
214
213
  # per prompt queued behind it and a command_queued per command waiting
215
214
  # for its end (spec/shared/turn_snapshot.json pins both sides). The TUI
@@ -63,6 +63,44 @@ module Samagotchi
63
63
  # * Optional at runtime: this module is never loaded unless explicitly
64
64
  # engaged as a transport.
65
65
  class Bridge
66
+ ENGINE_CALLS = {
67
+ active_cancel_controller: "turn-state monitor",
68
+ annotate_question: "question-desk control",
69
+ announce: "event-log monitor",
70
+ answer_question: "question-desk control",
71
+ cancel_current_turn!: "turn cancellation",
72
+ cancel_question: "question-desk control",
73
+ command_registry: "startup-built registry",
74
+ cut_for_steer: "steer-cut coordination",
75
+ drop_enqueued_id: "turn-state monitor",
76
+ enqueued_id?: "turn-state monitor",
77
+ event_count: "observer-registry monitor",
78
+ forget_enqueued_id: "turn-state monitor",
79
+ generation_snapshot: "generation-phase snapshot",
80
+ guardrail_warning: "startup-set warning reader",
81
+ init_tasks: "plugin-task monitor",
82
+ input_epoch: "waiting-steer monitor",
83
+ last_answer_message: "message snapshot under event lock",
84
+ messages_checkpoint: "replace-only message copy",
85
+ pending_question: "question-desk monitor",
86
+ plugin_warning: "warning-state reader",
87
+ recap: "recap-job reference",
88
+ recap_override: "session-setting reader",
89
+ relay_desk: "relay-store reference; status is monitor-protected",
90
+ request_recap: "idle-recap monitor",
91
+ reserve_enqueued_id: "turn-state monitor",
92
+ "running_turn_messages=": "callback writer; Bridge lifecycle",
93
+ saved_recap: "recap mutex; replace-only session messages",
94
+ session: "session reference; messages are replace-only",
95
+ session_state_snapshot: "snapshot; event lock for consistency",
96
+ stats_snapshot: "stats snapshot; may probe model",
97
+ steer_cut_after: "per-read model setting",
98
+ subscribe: "observer-registry monitor",
99
+ synchronize_events: "event-log monitor",
100
+ turn_running?: "turn-state monitor",
101
+ unsubscribe: "observer-registry monitor"
102
+ }.freeze
103
+
66
104
  DEFAULT_BIND = "127.0.0.1"
67
105
  DEFAULT_RING_CAPACITY = 256
68
106
  DEFAULT_HEARTBEAT_INTERVAL = 15.0
@@ -1399,10 +1437,14 @@ module Samagotchi
1399
1437
  end
1400
1438
 
1401
1439
  # Read-only snapshot surface. AC #4: too-old reconnects re-derive state
1402
- # from here.
1440
+ # from here. Read under the event lock, as snapshot_frame and tail_frame:
1441
+ # the state and its event_seq/event_id are one step of the event log.
1403
1442
  def handle_state(_session_id, _body = nil)
1404
- state = @engine.session_state_snapshot
1405
- [{}, 200, { session_id: @session_id, session_state_snapshot: state.merge(event_id: event_id(state[:event_seq])) }]
1443
+ state = @engine.synchronize_events do
1444
+ snap = @engine.session_state_snapshot
1445
+ snap.merge(event_id: event_id(snap[:event_seq]))
1446
+ end
1447
+ [{}, 200, { session_id: @session_id, session_state_snapshot: state }]
1406
1448
  end
1407
1449
 
1408
1450
  # /stats for an attached client: the metrics, with the window and prompt
@@ -83,7 +83,8 @@ module Samagotchi
83
83
  private_class_method :answer_of
84
84
 
85
85
  # A 0.157 record's class-file hooks: they no longer load, and only an
86
- # upgrade from a source that has moved them (or an uninstall) clears it.
86
+ # upgrade from a source that has moved them (or an uninstall) clears it
87
+ # (compat shim retired_class_file_hooks: Compat::SHIMS).
87
88
  def retired_hooks(bundle)
88
89
  Check::Finding.new(level: :warn, code: :"hooks-retired", file: "hooks/", line: nil,
89
90
  message: MemoryBundle::Manifest::HooksRetired::WORDS,
@@ -1,11 +1,11 @@
1
1
  ---
2
2
  name: inline-widgets
3
- version: 0.1.0
3
+ version: 0.1.1
4
4
  scope: system
5
5
  description: "Teaches the model the chi-ui blocks chi web draws: picks (rows of options that fill your reply) and walk (a scenario stepped through)"
6
6
  trust_level: reviewed
7
7
  plugin:
8
8
  file: plugin.rb
9
- sha256: sha256:24ad0c3f0ffb592826b4a7389111d76723e9f28ea4d94ab63abda7986d3311bb
9
+ sha256: sha256:e54a0096ba3b20ccf6bbca2798cb53afd86986a2cb7bee1c02e5520f2ddb5033
10
10
  # chi.prompt_section is 0.132.0's; the web draws chi-ui blocks only from the next release
11
11
  requires_chi: ">= 0.155.0"
@@ -9,8 +9,11 @@
9
9
  #
10
10
  # The text is eval 0013's round-2 hint, split in two. It is static, so the
11
11
  # prompt cache keeps: same text at every build. A delegate child's answer is
12
- # read by its parent, not drawn for a user, and a one-shot (-p --non-interactive)
13
- # prints to a terminal: neither gets a section.
12
+ # read by its parent, not drawn for a user, a one-shot (-p --non-interactive)
13
+ # prints to a terminal, and a review session (chi review) is read by its
14
+ # participants, whose page draws no widgets: none of them gets a section. A
15
+ # working session the owner pairs in keeps them: the owner's page draws them,
16
+ # and a participant invited later mustn't change the prompt (the cache).
14
17
  class Plugin
15
18
  PICKS = <<~TEXT
16
19
  The web UI draws fenced ```chi-ui code blocks (YAML inside) as interactive widgets; the terminal shows their source. Use one whenever it helps the user more than prose: a widget replaces the long explanation, it doesn't sit beside one. Never use one for what markdown shows well (tables, lists, key-value). At most one widget per answer; keep the prose around it to a few sentences and don't repeat the widget's content.
@@ -71,6 +74,7 @@ class Plugin
71
74
 
72
75
  private
73
76
 
74
- # Whether the session's answers reach a web page that draws them.
75
- def drawn?(ctx) = ctx.frontend != :one_shot && !ctx.delegate?
77
+ # Whether the session's answers reach a web page that draws them. Decided by
78
+ # the session's kind, so the same at every build.
79
+ def drawn?(ctx) = ctx.frontend != :one_shot && !ctx.delegate? && !ctx.review?
76
80
  end
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: samagotchi-system
3
- version: 0.163.0
3
+ version: 0.165.0
4
4
  scope: system
5
5
  description: Default system memories — identity, self map, config modification protocol, memory guide and the delegated-session rules
6
6
  files:
@@ -10,6 +10,7 @@ require_relative "bundler_env"
10
10
  require_relative "installed_gem"
11
11
  require_relative "log"
12
12
  require_relative "paths"
13
+ require_relative "state_format"
13
14
  require_relative "version"
14
15
 
15
16
  module Samagotchi
@@ -40,6 +41,23 @@ module Samagotchi
40
41
  PROBE = "require 'json'; print JSON.generate('ruby' => RbConfig.ruby, 'gem_home' => Gem.dir, " \
41
42
  "'gem_path' => Gem.path.join(File::PATH_SEPARATOR))"
42
43
  GEMSPEC = /\Asamagotchi-(#{Gem::Version::VERSION_PATTERN})\.gemspec\z/
44
+ # home.json's format (document members only), in its version key. A
45
+ # home.json with no version is one from before it (the same members); a
46
+ # newer chi's keeps its version and the keys this one doesn't know
47
+ # through a write of the same home (#write!). Record.from_h checks the
48
+ # members.
49
+ STATE_FORMAT_VERSION = 1
50
+ STATE_FORMAT = StateFormat.new(
51
+ version: STATE_FORMAT_VERSION, members: [],
52
+ document_members: [
53
+ StateFormat.required(:ruby),
54
+ StateFormat.required(:gem_home),
55
+ StateFormat.required(:gem_path),
56
+ StateFormat.added(:mise, in_version: 1, default: nil),
57
+ StateFormat.added(:set_at, in_version: 1, default: nil),
58
+ StateFormat.added(:set_by_version, in_version: 1, default: nil)
59
+ ]
60
+ )
43
61
 
44
62
  class Invalid < StandardError
45
63
  end
@@ -132,7 +150,7 @@ module Samagotchi
132
150
  data = JSON.parse(File.read(path))
133
151
  raise Invalid, "#{Paths.tilde(path)} is not a JSON object" unless data.is_a?(Hash)
134
152
 
135
- Record.from_h(data)
153
+ Record.from_h(fields(STATE_FORMAT.read(data, collection: nil)))
136
154
  rescue JSON::ParserError, SystemCallError => e
137
155
  raise Invalid, "#{Paths.tilde(path)}: #{e.message.lines.first.to_s.strip}"
138
156
  rescue Invalid => e
@@ -238,12 +256,36 @@ module Samagotchi
238
256
  end
239
257
 
240
258
  # @raise [SystemCallError]
259
+ # A home.json naming the same home (its ruby and gem_home) keeps its
260
+ # version and the keys this chi doesn't know; another home's are its
261
+ # own, so they go (as an install journal for another target's do).
241
262
  def write!(home, path: self.path)
263
+ earlier = stored_document(path)
264
+ same = earlier && earlier.attributes.values_at(:ruby, :gem_home) == [home.ruby, home.gem_home]
265
+ document = (same ? earlier : STATE_FORMAT.read({}, collection: nil))
266
+ .with(attributes: home.to_h.transform_keys(&:to_sym))
267
+ body = STATE_FORMAT.write(document, collection: nil, updated_at: nil)
242
268
  FileUtils.mkdir_p(File.dirname(path))
243
- AtomicFile.write(path, "#{JSON.pretty_generate(home.to_h)}\n", perm: 0o644)
269
+ AtomicFile.write(path, "#{JSON.pretty_generate(body)}\n", perm: 0o644)
244
270
  home
245
271
  end
246
272
 
273
+ # A document's members as Record.from_h takes them: a missing required
274
+ # one left out.
275
+ def fields(document)
276
+ document.attributes.reject { |_key, value| value.equal?(StateFormat::REQUIRED) }.transform_keys(&:to_s)
277
+ end
278
+
279
+ # home.json as STATE_FORMAT reads it, nil without one or when it doesn't
280
+ # read (a write replaces it).
281
+ # @return [StateFormat::Document, nil]
282
+ def stored_document(path)
283
+ data = JSON.parse(File.read(path))
284
+ data.is_a?(Hash) ? STATE_FORMAT.read(data, collection: nil) : nil
285
+ rescue JSON::ParserError, SystemCallError
286
+ nil
287
+ end
288
+
247
289
  # The first record, once, from an installed chi (chi bootstrap, chi
248
290
  # update): of the macOS helper's ruby (when its launch file names one
249
291
  # whose newest chi is at least this one: the Ruby it already runs) and