samagotchi 0.164.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 (85) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +52 -1
  3. data/docs/architecture.md +7 -5
  4. data/docs/cli.md +20 -13
  5. data/docs/configuration.md +5 -1
  6. data/docs/guardrails.md +13 -16
  7. data/docs/internals/block-renderers.md +1 -1
  8. data/docs/internals/bridge.md +4 -3
  9. data/docs/internals/bundles.md +4 -2
  10. data/docs/internals/inline-widgets.md +8 -1
  11. data/docs/internals/web-frontend.md +36 -9
  12. data/docs/memory.md +12 -7
  13. data/docs/plugins.md +6 -4
  14. data/docs/releasing.md +6 -2
  15. data/docs/scheduling.md +25 -3
  16. data/docs/sessions.md +8 -6
  17. data/docs/testing.md +28 -4
  18. data/lib/samagotchi/block_renderers.rb +3 -6
  19. data/lib/samagotchi/bridge/card_store.rb +2 -1
  20. data/lib/samagotchi/bridge/turn_accumulator.rb +7 -8
  21. data/lib/samagotchi/bridge.rb +45 -3
  22. data/lib/samagotchi/bundle_command/installed_check.rb +2 -1
  23. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  24. data/lib/samagotchi/chi_home.rb +44 -2
  25. data/lib/samagotchi/client_id.rb +34 -3
  26. data/lib/samagotchi/compat.rb +36 -0
  27. data/lib/samagotchi/context_command.rb +3 -0
  28. data/lib/samagotchi/context_providers.rb +5 -6
  29. data/lib/samagotchi/context_sources.rb +2 -2
  30. data/lib/samagotchi/continue_intent.rb +50 -5
  31. data/lib/samagotchi/events.rb +4 -4
  32. data/lib/samagotchi/extension_load.rb +2 -1
  33. data/lib/samagotchi/guardrails/child_boundary.rb +7 -27
  34. data/lib/samagotchi/guardrails/rules.rb +11 -9
  35. data/lib/samagotchi/guardrails/targets.rb +3 -4
  36. data/lib/samagotchi/inline_widgets.rb +16 -1
  37. data/lib/samagotchi/memory_bundle/provenance.rb +46 -4
  38. data/lib/samagotchi/memory_bundle/status.rb +2 -1
  39. data/lib/samagotchi/memory_command.rb +3 -0
  40. data/lib/samagotchi/memory_orphans.rb +4 -7
  41. data/lib/samagotchi/memory_paths.rb +64 -7
  42. data/lib/samagotchi/memory_usage.rb +1 -1
  43. data/lib/samagotchi/plugin/sessions.rb +4 -2
  44. data/lib/samagotchi/project_command.rb +4 -1
  45. data/lib/samagotchi/project_id_clash.rb +37 -26
  46. data/lib/samagotchi/project_init.rb +24 -7
  47. data/lib/samagotchi/reply_wait/poll.rb +2 -1
  48. data/lib/samagotchi/schedules.rb +124 -106
  49. data/lib/samagotchi/send_command.rb +71 -18
  50. data/lib/samagotchi/session.rb +3 -2
  51. data/lib/samagotchi/session_access/local.rb +19 -2
  52. data/lib/samagotchi/session_access/remote.rb +15 -4
  53. data/lib/samagotchi/session_chain/links.rb +109 -0
  54. data/lib/samagotchi/session_chain.rb +7 -19
  55. data/lib/samagotchi/session_continue.rb +138 -54
  56. data/lib/samagotchi/session_inbox_delivery.rb +57 -38
  57. data/lib/samagotchi/session_manager/delivery.rb +104 -18
  58. data/lib/samagotchi/session_manager/removal.rb +13 -7
  59. data/lib/samagotchi/session_manager.rb +1 -0
  60. data/lib/samagotchi/session_retention.rb +20 -10
  61. data/lib/samagotchi/session_setup.rb +31 -1
  62. data/lib/samagotchi/state_format.rb +12 -8
  63. data/lib/samagotchi/terminal_ui/attach_launcher.rb +6 -7
  64. data/lib/samagotchi/terminal_ui.rb +20 -9
  65. data/lib/samagotchi/tools/delegate.rb +2 -1
  66. data/lib/samagotchi/verify_fresh.rb +4 -1
  67. data/lib/samagotchi/version.rb +1 -1
  68. data/lib/samagotchi/web/public/activity.js +2 -2
  69. data/lib/samagotchi/web/public/app.js +13 -13
  70. data/lib/samagotchi/web/public/bar_fold.js +293 -0
  71. data/lib/samagotchi/web/public/card.js +1 -1
  72. data/lib/samagotchi/web/public/composer_mode.js +5 -7
  73. data/lib/samagotchi/web/public/index.html +132 -65
  74. data/lib/samagotchi/web/public/info_bar.js +28 -16
  75. data/lib/samagotchi/web/public/info_bar_model.js +70 -1
  76. data/lib/samagotchi/web/public/more_sheet.js +98 -40
  77. data/lib/samagotchi/web/public/stage_view.js +3 -1
  78. data/lib/samagotchi/web/public/stream_handlers.js +1 -1
  79. data/lib/samagotchi/web/public/turn_events.js +0 -122
  80. data/lib/samagotchi/web/public/turn_model.js +1 -1
  81. data/lib/samagotchi/web/public/widget_picks.js +18 -3
  82. data/lib/samagotchi/web/session_control.rb +15 -2
  83. data/lib/samagotchi/web/session_create.rb +4 -2
  84. data/lib/samagotchi/web/update_check.rb +27 -8
  85. metadata +3 -1
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
 
@@ -303,7 +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.
306
- - 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 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*).
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*).
307
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`.
308
310
 
309
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)`.
@@ -358,12 +360,12 @@ A session can **continue** an earlier one: "the next run of the same routine" (a
358
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.
359
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.
360
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.
361
- - **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.
362
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.
363
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`.
364
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.
365
367
  - **CLI:** `chi send --new --continues (ID|PREFIX|last:ID) [--model M] [-m TEXT]` (see *Starting a session*).
366
- - **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 message to an archived link that nobody continued brings it back (a human's input), it doesn't continue the chain. 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. 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.
367
369
 
368
370
  ## Schedules
369
371
 
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
@@ -105,13 +105,10 @@ module Samagotchi
105
105
  return nil unless for_installed.any? { |renderer| renderer.bundle == bundle && renderer.files.include?(file) }
106
106
 
107
107
  provenance = MemoryBundle::Provenance.new(name: bundle)
108
- path = File.join(provenance.scripts_dir, file)
109
- recorded = provenance.record&.scripts&.fetch(file, nil)
110
- raise Invalid, "bundle #{bundle}'s scripts/#{file} isn't among its installed scripts (reinstall the bundle)" if recorded.to_s.empty?
111
- raise Invalid, "bundle #{bundle}'s scripts/#{file} is missing (reinstall the bundle)" unless File.file?(path)
112
- return path if MemoryBundle::Provenance.sha_matches?(path, recorded)
108
+ failure = provenance.script_failure(file, provenance.record&.scripts&.fetch(file, nil))
109
+ raise Invalid, failure if failure
113
110
 
114
- raise Invalid, "bundle #{bundle}'s scripts/#{file} differs from the installed one (reinstall the bundle)"
111
+ File.join(provenance.scripts_dir, file)
115
112
  end
116
113
 
117
114
  # Its parsed renderers; a kept list that doesn't parse is the record's
@@ -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,6 +1,6 @@
1
1
  ---
2
2
  name: samagotchi-system
3
- version: 0.164.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
@@ -11,6 +11,10 @@ module Samagotchi
11
11
  WEB_RESTART = "web:restart"
12
12
  # A web page's first prompt when creating a session.
13
13
  WEB_CREATE = "web:create"
14
+ # The owner's turn or command route (POST /api/sessions/:id/turn,
15
+ # /command) given no client_id (a script, curl with the owner's token):
16
+ # named at that seam, a web tab's rights, never a silent nil.
17
+ WEB_UNNAMED = "web:unnamed"
14
18
  # An attached chi TUI: tui:<pid>.
15
19
  TUI_PREFIX = "tui:"
16
20
  # chi send's turns and commands.
@@ -45,9 +49,13 @@ module Samagotchi
45
49
 
46
50
  # Input a human typed: a web tab, a chi TUI, chi send, a participant
47
51
  # (review:, a person or an agent they run: never automatic input), and
48
- # nil (a worker's initial prompt; a web client may send none). An
49
- # allowlist: delegates, plugins, reminders, context changes and any id
50
- # chi doesn't know are not.
52
+ # nil, which reaches only a worker's own seams: its initial prompt
53
+ # (spawn_session saves no first_turn_client_id for a person's), a Bridge
54
+ # POST /turn naming none (the Bridge's secret holder: a local TUI or chi
55
+ # web, which names its sender) and an input file from an older chi.
56
+ # SessionManager.deliver_turn refuses nil; chi web's turn and command routes
57
+ # name it (WEB_UNNAMED). An allowlist: delegates, plugins, reminders, context
58
+ # changes and any id chi doesn't know are not.
51
59
  HUMAN_PREFIXES = [WEB_PREFIX, TUI_PREFIX, REVIEW_PREFIX].freeze
52
60
  HUMAN_IDS = [CLI_SEND].freeze
53
61
 
@@ -58,6 +66,14 @@ module Samagotchi
58
66
  # A turn's origin by its sender (#origin, LastTurn#origin): the ids chi
59
67
  # runs turns for on its own, by prefix, and a participant's ("review");
60
68
  # system:reminder is "reminder", anything else "client".
69
+ # Which SessionInbox::WakePolicy row a turn delivery from a sender reads
70
+ # (#wake_kind): a person's (:send: un-stops, un-archives) by allowlist,
71
+ # like HUMAN_PREFIXES; the unattended senders' own rows; any other id
72
+ # the safe :automatic row (no un-stop, no un-archive).
73
+ PERSON_WAKE_PREFIXES = [WEB_PREFIX, TUI_PREFIX].freeze
74
+ WAKE_PREFIXES = { SCHEDULE_PREFIX => :schedule, DELEGATE_PREFIX => :delegate,
75
+ REVIEW_PREFIX => :participant }.freeze
76
+
61
77
  ORIGIN_PREFIXES = { DELEGATE_PREFIX => "delegate", CHILD_PREFIX => "delegate_report",
62
78
  CONTEXT_PREFIX => "context", TASK_PREFIX => "task", REVIEW_PREFIX => "review",
63
79
  SCHEDULE_PREFIX => "schedule" }.freeze
@@ -93,6 +109,21 @@ module Samagotchi
93
109
  HUMAN_IDS.include?(id) || HUMAN_PREFIXES.any? { |prefix| id.start_with?(prefix) }
94
110
  end
95
111
 
112
+ # The WakePolicy row a turn delivery from +client_id+ reads (deliver_turn's
113
+ # two liveness checks): :send for a person (a web tab, a chi TUI, chi
114
+ # send), :schedule, :plugin, :delegate or :participant for those
115
+ # senders, :automatic for anything else (nil too: deliver_turn refuses it
116
+ # first). Only :send un-stops a stopped session or starts an archived one.
117
+ # @return [Symbol]
118
+ def wake_kind(client_id)
119
+ id = client_id.to_s
120
+ return :send if id == CLI_SEND || PERSON_WAKE_PREFIXES.any? { |prefix| id.start_with?(prefix) }
121
+ return :plugin if id == PLUGIN
122
+
123
+ WAKE_PREFIXES.each { |prefix, kind| return kind if id.start_with?(prefix) }
124
+ :automatic
125
+ end
126
+
96
127
  # The client id a participant's turn carries (chi web's, from their
97
128
  # grant): review:<participant id>.
98
129
  def review(participant_id) = "#{REVIEW_PREFIX}#{participant_id}"
@@ -6,8 +6,44 @@ require_relative "version"
6
6
  module Samagotchi
7
7
  # The compatibility decision for state and bridge data from a chi version.
8
8
  module Compat
9
+ # Code kept only for another chi version's data or protocol, and the
10
+ # release after which it goes. +remove_after+ nil: the owner hasn't
11
+ # decided (kept until then). spec/compat_spec.rb fails once VERSION
12
+ # passes a shim's +remove_after+, naming it. Each Ruby file names its
13
+ # shim's id in a comment ("compat shim <id>").
14
+ # @!attribute files [Array<String>] where the shim lives (from the repository root)
15
+ Shim = Data.define(:id, :added_in, :remove_after, :files, :what)
16
+
17
+ SHIMS = [
18
+ Shim.new(id: :cards_v1_seed, added_in: "0.151.0", remove_after: "0.170.0",
19
+ files: ["lib/samagotchi/bridge/card_store.rb"],
20
+ what: "CardStore#seed_v1 reads a cards.json from before the turn log; its comment says a retention " \
21
+ "period after the release that wrote version 2 (0.151.0, 2026-11-05)"),
22
+ Shim.new(id: :merge_inference, added_in: "0.157.0", remove_after: "0.165.0",
23
+ files: ["lib/samagotchi/reply_wait/poll.rb", "lib/samagotchi/tools/delegate.rb"],
24
+ what: "a wait infers a merged steer when the worker wrote no merge record (a 0.156 worker)"),
25
+ Shim.new(id: :session_not_found_words, added_in: "0.156.0", remove_after: "0.165.0",
26
+ files: ["lib/samagotchi/session_access/remote.rb"],
27
+ what: "SESSION_NOT_FOUND also reads chi web 0.155.0's \"Session not found: X\" (its comment: compat N-1)"),
28
+ Shim.new(id: :remote_refusal_details, added_in: "0.122.0", remove_after: "0.165.0",
29
+ files: ["lib/samagotchi/session_access/remote.rb"],
30
+ what: "context_missing? and no_provider? read an older chi web's 404 detail words, before their error codes"),
31
+ Shim.new(id: :retired_class_file_hooks, added_in: "0.158.0", remove_after: "0.166.0",
32
+ files: ["lib/samagotchi/extension_load.rb", "lib/samagotchi/memory_bundle/status.rb",
33
+ "lib/samagotchi/bundle_command/installed_check.rb"],
34
+ what: "a 0.157 install record's class-file hooks: announced as not loading, shown and checked until " \
35
+ "an upgrade or uninstall clears them (installed state, not protocol)")
36
+ ].freeze
37
+
9
38
  module_function
10
39
 
40
+ # The shims +version+ has passed the remove_after of.
41
+ # @return [Array<Shim>]
42
+ def overdue_shims(version: VERSION, shims: SHIMS)
43
+ current = Gem::Version.new(version)
44
+ shims.select { |shim| shim.remove_after && current > Gem::Version.new(shim.remove_after) }
45
+ end
46
+
11
47
  def verdict(worker_version:, version: VERSION, worker_protocol: nil, protocol: nil)
12
48
  return :refused if protocol && worker_protocol.to_i > protocol
13
49
 
@@ -130,6 +130,9 @@ module Samagotchi
130
130
  rescue ContextSources::Invalid => e
131
131
  error_line("#{command_name}: #{e.message}")
132
132
  CLI::Exit::FAILED
133
+ rescue MemoryPaths::ProjectIdConflict => e
134
+ error_line("#{command_name}: #{e.message}")
135
+ CLI::Exit::FAILED
133
136
  end
134
137
 
135
138
  private
@@ -149,8 +149,9 @@ module Samagotchi
149
149
  # installed (they run outside the guardrails gate, as a plugin loads:
150
150
  # checked the same way).
151
151
  # @return [String]
152
- # @raise [Invalid] the bundle is gone, a script changed, or this chi
153
- # doesn't meet the bundle's requires_chi
152
+ # @raise [Invalid] the bundle is gone, a script is gone, unrecorded or
153
+ # changed (Provenance#script_failure), or this chi doesn't meet the
154
+ # bundle's requires_chi
154
155
  def command_for(source)
155
156
  return source.cmd unless source.provider
156
157
 
@@ -165,10 +166,8 @@ module Samagotchi
165
166
  end
166
167
 
167
168
  record.scripts.each do |file, sha|
168
- path = File.join(provenance.scripts_dir, file)
169
- next if File.file?(path) && MemoryBundle::Provenance.sha_matches?(path, sha)
170
-
171
- raise Invalid, "bundle #{source.provider}'s scripts/#{file} differs from the installed one (reinstall the bundle)"
169
+ failure = provenance.script_failure(file, sha)
170
+ raise Invalid, failure if failure
172
171
  end
173
172
  source.cmd.gsub(BUNDLE_DIR) { Shellwords.escape(provenance.bundle_dir) }.gsub(RUBY) { Shellwords.escape(RbConfig.ruby) }
174
173
  end
@@ -636,10 +636,10 @@ module Samagotchi
636
636
  # @param project_root [String, nil] Session#project_root
637
637
  # @param project_id [String, nil] Session#project_id (a marked project's
638
638
  # id keys its folder: MemoryPaths.key_for)
639
- def project_location_for(project_root, project_id: nil, state_dir: nil)
639
+ def project_location_for(project_root, project_id: nil, state_dir: nil, env: ENV)
640
640
  return nil if project_root.to_s.empty?
641
641
 
642
- project_location(MemoryPaths.key_for(root: project_root, id: project_id), state_dir: state_dir)
642
+ project_location(MemoryPaths.key_for(root: project_root, id: project_id, env: env), state_dir: state_dir)
643
643
  end
644
644
 
645
645
  # A session's sources: its own, then the project's it doesn't shadow