samagotchi 0.164.0 → 0.166.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +88 -1
- data/docs/architecture.md +7 -5
- data/docs/cli.md +23 -12
- data/docs/configuration.md +8 -2
- data/docs/guardrails.md +19 -18
- data/docs/internals/block-renderers.md +1 -1
- data/docs/internals/bridge.md +10 -3
- data/docs/internals/bundles.md +4 -2
- data/docs/internals/inline-widgets.md +8 -1
- data/docs/internals/remote-sessions.md +1 -1
- data/docs/internals/web-frontend.md +73 -13
- data/docs/memory.md +12 -7
- data/docs/plugins.md +6 -4
- data/docs/releasing.md +17 -4
- data/docs/scheduling.md +25 -3
- data/docs/sessions.md +12 -10
- data/docs/testing.md +37 -4
- data/lib/samagotchi/block_renderers.rb +3 -6
- data/lib/samagotchi/bridge/card_store.rb +2 -1
- data/lib/samagotchi/bridge/turn_accumulator.rb +7 -8
- data/lib/samagotchi/bridge.rb +45 -3
- data/lib/samagotchi/bundle_command/installed_check.rb +2 -1
- data/lib/samagotchi/bundles/system/manifest.yml +1 -1
- data/lib/samagotchi/chi_home.rb +44 -2
- data/lib/samagotchi/client_id.rb +34 -3
- data/lib/samagotchi/compat.rb +34 -0
- data/lib/samagotchi/context_command.rb +3 -0
- data/lib/samagotchi/context_providers.rb +5 -6
- data/lib/samagotchi/context_sources.rb +2 -2
- data/lib/samagotchi/continue_intent.rb +50 -5
- data/lib/samagotchi/events.rb +4 -4
- data/lib/samagotchi/extension_load.rb +2 -1
- data/lib/samagotchi/guardrails/approvals.rb +36 -9
- data/lib/samagotchi/guardrails/child_boundary.rb +7 -27
- data/lib/samagotchi/guardrails/rules.rb +11 -9
- data/lib/samagotchi/guardrails/targets.rb +3 -4
- data/lib/samagotchi/inline_widgets.rb +16 -1
- data/lib/samagotchi/memory_bundle/provenance.rb +46 -4
- data/lib/samagotchi/memory_bundle/status.rb +2 -1
- data/lib/samagotchi/memory_command.rb +3 -0
- data/lib/samagotchi/memory_orphans.rb +4 -7
- data/lib/samagotchi/memory_paths.rb +64 -7
- data/lib/samagotchi/memory_usage.rb +1 -1
- data/lib/samagotchi/plugin/sessions.rb +8 -3
- data/lib/samagotchi/project_command.rb +4 -1
- data/lib/samagotchi/project_id_clash.rb +37 -26
- data/lib/samagotchi/project_init.rb +24 -7
- data/lib/samagotchi/reply_wait/poll.rb +4 -14
- data/lib/samagotchi/reply_wait.rb +0 -23
- data/lib/samagotchi/run_options.rb +1 -1
- data/lib/samagotchi/schedules.rb +124 -106
- data/lib/samagotchi/send_command.rb +71 -18
- data/lib/samagotchi/session.rb +3 -2
- data/lib/samagotchi/session_access/local.rb +19 -2
- data/lib/samagotchi/session_access/remote.rb +13 -17
- data/lib/samagotchi/session_chain/links.rb +109 -0
- data/lib/samagotchi/session_chain.rb +7 -19
- data/lib/samagotchi/session_continue.rb +138 -54
- data/lib/samagotchi/session_inbox.rb +1 -1
- data/lib/samagotchi/session_inbox_delivery.rb +57 -38
- data/lib/samagotchi/session_manager/delivery.rb +104 -18
- data/lib/samagotchi/session_manager/removal.rb +13 -7
- data/lib/samagotchi/session_manager.rb +1 -0
- data/lib/samagotchi/session_retention.rb +20 -10
- data/lib/samagotchi/session_setup.rb +31 -1
- data/lib/samagotchi/state_format.rb +12 -8
- data/lib/samagotchi/terminal_ui/attach_launcher.rb +6 -7
- data/lib/samagotchi/terminal_ui.rb +20 -9
- data/lib/samagotchi/tools/delegate.rb +2 -3
- data/lib/samagotchi/verify_fresh.rb +4 -1
- data/lib/samagotchi/version.rb +1 -1
- data/lib/samagotchi/web/public/activity.js +2 -2
- data/lib/samagotchi/web/public/app.js +28 -21
- data/lib/samagotchi/web/public/auth_lost.js +3 -1
- data/lib/samagotchi/web/public/bar_fold.js +293 -0
- data/lib/samagotchi/web/public/card.js +1 -1
- data/lib/samagotchi/web/public/chip_popover.js +5 -1
- data/lib/samagotchi/web/public/composer_mode.js +5 -7
- data/lib/samagotchi/web/public/delivery_line.js +19 -4
- data/lib/samagotchi/web/public/index.html +242 -94
- data/lib/samagotchi/web/public/info_bar.js +28 -16
- data/lib/samagotchi/web/public/info_bar_model.js +76 -2
- data/lib/samagotchi/web/public/live_timing.js +3 -0
- data/lib/samagotchi/web/public/more_sheet.js +98 -40
- data/lib/samagotchi/web/public/resync_reach.js +59 -0
- data/lib/samagotchi/web/public/session_fields.js +1 -0
- data/lib/samagotchi/web/public/session_state.js +5 -0
- data/lib/samagotchi/web/public/stage_frame.js +4 -2
- data/lib/samagotchi/web/public/stage_stall.js +134 -0
- data/lib/samagotchi/web/public/stage_view.js +78 -7
- data/lib/samagotchi/web/public/stream_handlers.js +1 -1
- data/lib/samagotchi/web/public/turn_events.js +0 -122
- data/lib/samagotchi/web/public/turn_model.js +1 -1
- data/lib/samagotchi/web/public/widget_picks.js +18 -3
- data/lib/samagotchi/web/session_control.rb +15 -2
- data/lib/samagotchi/web/session_create.rb +4 -2
- data/lib/samagotchi/web/token.rb +2 -2
- data/lib/samagotchi/web/update_check.rb +27 -8
- metadata +5 -1
data/docs/sessions.md
CHANGED
|
@@ -8,7 +8,7 @@ Sessions are plain files — no DB. Each session is `~/.local/state/samagotchi/s
|
|
|
8
8
|
|
|
9
9
|
**Revise stacks:** a web Revise turn (POST /turn `revises: {turn_id}`, the answer it rewrites) stamps its opening message (its prompt) with `revises: {turn_id}` at the turn's end, only when the turn completed with an answer (`AnswerTail`): a failed, canceled or empty turn revised nothing (`TurnStages::VerifyAnchors#stamp_opening`). A draft no prompt carries (a stale page, a rolled-back turn) is no target: no stamp. A draft a stamped turn already revised is re-targeted to its stack's top, the newest version, so a stack is a chain `v1 ← v2 ← v3`. Like `verify`, it is metadata only, never added to the prompt (no change to a request's bytes); chi web's history passes it on the opening message (and on a wake turn's note), and `:turn_completed` carries the stamped `revises` (the participant view's too). The history also marks a Verify turn's opening `verify: true`, and so does its live end event (`:turn_completed`'s `verify: true`, with its `turn_id`): the page offers no Revise on its answer. The web page draws the stacks from these stamps (docs/cli.md, Revise). Like a Verify turn's, a Revise message waits for the running turn's end (`SessionInbox.turn_end_data?`; the Bridge takes either as `delivery: queue`, so it never cuts and its ack and `:turn_enqueued` say it queues), is sent only to a worker whose `bridge.json` names the `revise` feature (else 409 `revise_unavailable`), and a failed turn gives it back (`:prompt_restored`'s `revises`). Participants can't Revise: chi web and the Bridge drop it from their turns. Both anchors travel as one `TurnAnchors` inside chi; on the wire and in an input file each keeps its own key (`verify`, `revises`).
|
|
10
10
|
|
|
11
|
-
**Input files:** a message for a session's worker waits in `input/<timestamp>.json` (`SessionInbox.write_input`: `prompt`, `client_id`, `enqueued_id`, and `images`, `no_interrupt` and `delivery` when they apply; `delivery` is written only for `"queue"`). While a turn runs, the worker merges them at each step boundary in name order, except a queued one or one with images: those wait for the turn's end and run one turn each, in name order, and a file after them still merges (`Worker#pending_input_drain`). For each file it merges, before deleting it, the drain records which turn took it: `input/merged/<enqueued_id>` = `{"into": the turn's enqueued_id, "at"}` (`SessionInbox.mark_merged`; none for a turn without an id), so a wait for that message waits for that turn (`ReplyWait::Poll#follow_merge
|
|
11
|
+
**Input files:** a message for a session's worker waits in `input/<timestamp>.json` (`SessionInbox.write_input`: `prompt`, `client_id`, `enqueued_id`, and `images`, `no_interrupt` and `delivery` when they apply; `delivery` is written only for `"queue"`). While a turn runs, the worker merges them at each step boundary in name order, except a queued one or one with images: those wait for the turn's end and run one turn each, in name order, and a file after them still merges (`Worker#pending_input_drain`). For each file it merges, before deleting it, the drain records which turn took it: `input/merged/<enqueued_id>` = `{"into": the turn's enqueued_id, "at"}` (`SessionInbox.mark_merged`; none for a turn without an id), so a wait for that message waits for that turn (`ReplyWait::Poll#follow_merge`). A turn nobody typed (a reminder, a wake turn: a delegate report's, an attached context change's, a finished task's) gets an `enqueued_id` its worker mints as it runs, `wake-` and 16 hex digits (`Worker#wake_origin`), for its mark, `last_turn`, reply file and settle; the reports it merges keep id-less origins. Such a file, with a prompt, from the user, `chi send` or a delegating parent, also ends a running `task_wait` or `delegate_result` and hands a running `execute` over as a task after 3 s (`SessionInbox.steer_waiting?`, a peek the worker's turn polls through `Engine#input_waiting?`; never in a participant's turn): the file stays for the drain. A queue is sent only to a worker whose `bridge.json` names the `delivery` feature; an older one would steer it, so `SessionManager.deliver_turn` refuses it (409 `delivery_unavailable`), and any other 4xx the Bridge answers is a refusal too, never a fallback file (except a 413, a body over its size limit: that one still goes in as a file, its `delivery` kept). A session command recognized in a file runs without a turn; its outcome is kept at `input/settled/<enqueued_id>` (`completed`, `failed` for a command error, `canceled` with `cancel_reason` `busy` or `dropped` for one refused mid-turn or dropped as the worker left; `origin: command`) so `chi send --wait` ends instead of waiting for a turn that will not run, its detail saying `the command failed` or `the command was refused (busy)` rather than a turn's words. **Reply files:** a turn that ends with visible text leaves its reply in `output/<timestamp>.txt`, or `output/<timestamp>-<enqueued_id>.txt` when the turn ran an input file with an id (`SessionInbox.write_output`), and the session's `last_turn` keeps that `enqueued_id`; so a wait for one queued message (`chi send --queue --wait`, `ReplyWait`'s `turn:`) finds its own turn's reply or end, never another turn's. The names still sort by time, and every reader takes `*.txt`.
|
|
12
12
|
|
|
13
13
|
**Removing a queued message:** a message queued for after the running turn (`chi send --queue`, the web's Alt+Enter, `/queue TEXT` in a terminal), or one with images (it waits for the turn's end too), can be taken back while it still waits: the worker's Bridge (`POST /session/:id/turn/dequeue {enqueued_id}`, the `unqueue` feature) deletes its input file and every UI drops it (`:turn_dequeued`). It is a race with the turn's end, decided by the same rename the worker uses to take the file: once a turn took it the answer is `409 already_started` (it runs), and an id the worker no longer knows is `404 unknown_enqueued_id`. A plain message sent without `--queue` is not removable (`409 not_queued`): a running turn's next step may take it at any moment. A wait for its turn (`chi send --queue --wait`, a delegate follow-up's wait) ends at once with `removed` (the tombstone `input/removed/<enqueued_id>` says so), and a `chi -p` run whose queued prompt went ends with exit 1. The `200` carries the removed `prompt`: the web and the attached terminal put it back into the composer to edit (not its images). The images a removed message named stay in the session's `images/`. Not removable: a queued session command (`/queue /model x`: it waits in the worker, not in `input/`), and a message in a stopped worker's inbox (the next worker runs it).
|
|
14
14
|
|
|
@@ -23,21 +23,23 @@ 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
|
|
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
|
|
|
40
|
-
**A worker killed mid-turn:** while a turn runs, its worker keeps it on disk (`TurnCheckpoint`): the session file has the turn so far (the prompt from the turn's start, then the finished tool steps and lines merged into it) and `interrupted_turn: {id, started_at, at, iteration, enqueued_id}` (`enqueued_id`: the input the turn runs, so any process can tell which turn is running; a continue turn carries its offer turn's), written as the turn starts, at the loop's first iteration boundary and then at most every 10 s (`updated_at` moves with it). The turn's end saves the real messages without the mark. A worker that died without ending its turn (SIGKILL, a crash of the process) leaves the mark, and loses what came after its last written boundary: at most the last 10 s of steps, plus the step in flight. Each checkpoint write also saves the turn's metrics so far to `analytics.json` (tokens, speeds, timings, its finished tool calls), as the record a killed turn leaves: canceled, `cancellation_reason: worker_stopped`; the turn's own end writes over it. The next worker to start for the session (a `chi send`, `--resume`, `--attach`, the web), or a `chi --resume ID -p TEXT --non-interactive` run, settles the turn before anything else (`TurnCheckpoint.settle`, log `interrupted_turn_settled`): a note `the previous turn was cancelled (worker-stopped) after Ns` goes at the tail, the status goes idle and the mark goes; `last_turn` stays the previous turn's (a new one saved before the turn a `chi send --wait` woke the worker for would end that wait at once); the dead turn's end is recorded under its `enqueued_id` instead, in `<id>/input/settled/<enqueued_id>` (a `last_turn` record: canceled, `cancel_reason: worker_stopped`), which only a wait for that very turn reads (`chi send --queue --wait`, a `chi send --wait -m` to an idle session or `--new`, `chi send --wait ID --turn`, a continue's wait): it ends `canceled` with `cancel_reason: worker_stopped`, detail "its worker exited mid-turn", instead of timing out. A wake or reminder turn's settle is recorded under its worker-minted `wake-…` id the same way, and a message merged into a turn as a steer follows that turn's id (`input/merged/`). A wait with no turn id that saw the turn running ends the same way when the settle comes (`chi send --wait ID` with no message on a turn with no id, such as a 0.156 worker's reminder turn
|
|
42
|
+
**A worker killed mid-turn:** while a turn runs, its worker keeps it on disk (`TurnCheckpoint`): the session file has the turn so far (the prompt from the turn's start, then the finished tool steps and lines merged into it) and `interrupted_turn: {id, started_at, at, iteration, enqueued_id}` (`enqueued_id`: the input the turn runs, so any process can tell which turn is running; a continue turn carries its offer turn's), written as the turn starts, at the loop's first iteration boundary and then at most every 10 s (`updated_at` moves with it). The turn's end saves the real messages without the mark. A worker that died without ending its turn (SIGKILL, a crash of the process) leaves the mark, and loses what came after its last written boundary: at most the last 10 s of steps, plus the step in flight. Each checkpoint write also saves the turn's metrics so far to `analytics.json` (tokens, speeds, timings, its finished tool calls), as the record a killed turn leaves: canceled, `cancellation_reason: worker_stopped`; the turn's own end writes over it. The next worker to start for the session (a `chi send`, `--resume`, `--attach`, the web), or a `chi --resume ID -p TEXT --non-interactive` run, settles the turn before anything else (`TurnCheckpoint.settle`, log `interrupted_turn_settled`): a note `the previous turn was cancelled (worker-stopped) after Ns` goes at the tail, the status goes idle and the mark goes; `last_turn` stays the previous turn's (a new one saved before the turn a `chi send --wait` woke the worker for would end that wait at once); the dead turn's end is recorded under its `enqueued_id` instead, in `<id>/input/settled/<enqueued_id>` (a `last_turn` record: canceled, `cancel_reason: worker_stopped`), which only a wait for that very turn reads (`chi send --queue --wait`, a `chi send --wait -m` to an idle session or `--new`, `chi send --wait ID --turn`, a continue's wait): it ends `canceled` with `cancel_reason: worker_stopped`, detail "its worker exited mid-turn", instead of timing out. A wake or reminder turn's settle is recorded under its worker-minted `wake-…` id the same way, and a message merged into a turn as a steer follows that turn's id (`input/merged/`). A wait with no turn id that saw the turn running ends the same way when the settle comes (`chi send --wait ID` with no message on a turn with no id, such as a 0.156 worker's reminder turn), unless an input still waits or was claimed since: an unmerged message runs as its own turn next, and that turn's end is the answer. A reply the turn wrote before its worker died is still its answer. The session shows the turn's prompt and steps with that note; the dead turn is not run again, and the model reads on its next turn that it was cut.
|
|
41
43
|
|
|
42
44
|
**Stopping a worker:** `chi sessions stop ID` marks the session stopped (an `<id>/stopped` file holding when, `{"at"}`, not a session.json field, which a worker saving at that moment would write over; a resume removes it), sends its worker TERM, then CONT (a stopped worker, SIGSTOP or Ctrl-Z, runs its TERM handler only once continued, so it leaves at once instead of outliving the wait), and waits (up to 10 s) until the worker has let go of `owner.lock`. A running turn is canceled over the Bridge first, with reason `session_stopped` (the turn's line ends "(session stopped)", its note says `cancelled (session-stopped)`, and a command it was running says "stopped as the session was stopped"; a bare signal to the worker makes it "stopped by a signal to chi"; an older worker takes the reason as `manual`); the TERM stops whatever still runs as a Stop with reason `signal` and saves it (a spawned worker traps TERM, HUP and INT: `WorkerSignals`; a turn not ended within 3 s, 0.5 s after a stop or a second signal, is cut and the session saved as it was), and a stopped worker still saves its kept turn, since the marker, not the saved status, says stopped. Any TERM, HUP or INT does the same to a worker outside a stop: it leaves (log `worker stop reason=signal`) and the next send wakes a new one, so a `chi --resume ID` right after spawns a fresh worker. That is also how to restart a worker still running an older chi, which the attached terminal reports when a command or a question dismiss gets a 404, and the web when an answer, a dismiss, a command or a cancel does (`501 not_supported`; `BridgeClient.stale_worker_message`). A command this chi has that the older worker doesn't (`/llm-context`, the web's ⚙ panel, against a 0.39.0 worker) says the same, not `not a session command` (`SessionCommands.builtin_name`); a typo keeps its `400 unknown_command`. The web's `POST /api/sessions/:id/stop` waits the same way, for 2 s (the page's Stop shows the stop at once), or for the body's `wait` up to the same 10 s (`SessionManager::STOP_WAIT`): `chi --remote NAME sessions stop` sends it, so it waits as long as here. Before that stop, the page's `stop session` button asks what the worker still has that the user can stop: `GET /api/sessions/:id/holds` (owner-only) answers the worker's `holds` — the same list the exit ask's 409 carries — always an array, empty when there is no live worker, one from before the route, or one that did not answer. With something, a sheet (a bottom sheet on a phone, a popover at the button otherwise — `stop_sheet.js`) lists them, at most three of a kind named and `+N more`, and offers **Stop all** (`POST /api/sessions/:id/holds/stop` → `HoldStop#stop_all`, then the stop), **Stop session only** (the stop exactly as it was) or **Cancel**. Nothing to ask about is the plain confirm, one tap as before. Both buttons stay because a stop only TERMs the worker: its reminders die with it (a stop also deletes a restart's `reminders.json` no successor took yet, so a later resume doesn't bring them back), while a background task and a delegate are their own processes and keep running. A command sent during a turn that waits for its end (`/model X`, `!cmd`; see *Typing during a turn* in [cli.md](cli.md)) and hasn't run when the worker leaves (a stop, a crash) is answered `command_ran {status: "dropped"}`, so no UI keeps showing it waiting.
|
|
43
45
|
|
|
@@ -102,7 +104,7 @@ chi sessions clean --dry-run --days 7 # test sessions older than 7 da
|
|
|
102
104
|
- `Session.list` / `SessionManager.list_sessions` / `GET /api/sessions?sort=&order=&limit=&offset=` default to `updated_at desc` (newest activity first). Also supports `created_at`, `asc`. `X-Total-Count` header when paginated.
|
|
103
105
|
- Web UI (`chi web`): the page's scope is in its URL. Started in a project (a git repository or a `chi project init` folder), `chi web` opens `/?dir=<that folder>`: that project's sessions, and new sessions start in that folder; the header chip says `<project> · all`, and `all` opens the same place as `?scope=all` (every session; a new session there starts in chi web's start folder, shown on the start page, and cards name their folder; `← <project>` goes back to the project view it came from, or to the start folder's project). A bare `/` (the LAN link, the Home Screen app) is the start folder's project too: the folder chi web runs in, or `web.start_dir` / `chi web --start-dir DIR`; outside a project (no repository or marked folder) it shows every session. A pushed notification opens its session in that session's own project (`/?dir=<its project>#/s/<id>`; `?scope=all` outside a project). One server serves every project: a second `chi web` (from another repo) finds it through `GET /api/info` and prints (with `--open`, opens) its page for its own folder instead of starting another. The 3 latest sessions sit above the chat, and the grip on the chat's top edge — the same thin handle as the composer's, its twin — puts them away and brings them back: a drag up (or a click, or Enter/Space on it) hides them, a drag down (or a click) shows them again, and the choice is remembered. A hidden strip leaves its status in the top bar (`N sessions · ● 1 live · ● 1 waiting`, from the cards), and a click on that pill opens All sessions, without showing the strip first; there the pill shows whatever the strip's state, pressed, and a click on it goes back to the chat (as Esc does). In a window under 900 px wide, where the strip scrolls sideways, the grip stays under it, outside the scroller; a window under 700 px tall hides the strip by itself, so a question or approval card in the stage keeps room, and the grip shows it until the window is tall again. A parent and its delegates are one card there: its `▸ 2 delegates · 1 live · 1 waiting` chip (the waiting part in the attention colour, the card's border too; just `▸ 2 delegates` while the rows are open: they carry the marks then) opens their rows in a popover under it (a row per delegate at any depth, indented; a click opens that one, Esc or a click outside closes it, and the strip's order holds while it is open). A fork is a card of its own, and so is a delegate whose parent isn't listed (archived, another project), with its `↳ <parent>` chip; the pill counts cards, and every live or waiting session. "All sessions" (or `/`) opens every session at `#/sessions`; its header is the top bar's right end: a search over preview, id and status, the count, an `archived` toggle and Select (on a phone a row of its own under the bar). Esc or the pressed pill returns; where the sessions are stored is a faint line under the list. A card is its title on one line (an untitled session reads `Untitled` over its first message), a line under it (its recap, else its first message) and its meta row, with one mark per state and no status dot: a waiting card has its warn outline and its `question` (or `approval`…) chip, an errored one an `error` badge, a session a worker runs the `live` badge (not on a waiting card: waiting means a worker), and idle, completed and stopped ones are unmarked; a family's and a chain's rows the same. There a parent's card holds its delegates the same way, the chip opening their rows inside the card (each with an archive button on hover), open by itself while one of them waits on you; the count says `14 · 7 delegates` (`3 / 14` while a search narrows it), a search that matches a delegate shows its parent's card with the list open and the matching rows marked, and select mode picks cards (archiving a parent takes its delegates). The open session is in the URL (`#/s/<id>`), so a reload or a copied link opens it again; the chi logo top left goes back to the empty start for a new session. The message box grows with its text; drag its top edge to keep it taller (double-click resets). A file in a tool row (a read, edit or write's title) and its diff lines are refs: hover one and click to open the current file in your editor at that line, on this machine only (`web.editor`; the browser's "always allow" for the page's port and VS Code's "allow opening local files" are asked once; see [Opening files from chi web](configuration.md#opening-files-from-chi-web)). So are an edit or write approval card's paths (at the first line the dry run changes) and its diff lines, before you approve, and the numbered lines of a read's output: `lines 40–60` under it opens the text as read, numbered, when the output is the file as-is (not the head/tail preview of a big file, an error or an image; no numbers after a cut). A `path:line` (or `path:line-line`) in an answer or a step's text is one too once the turn has ended, and after a reload, when it names a file a row or card on the page touched: the path under the session's folder, else the one touched file it ends with (a bare `app.js:12` when only one touched file is named so; two such files make it none); a path without a line counts only when it is a touched file exactly. Code blocks, links, bare URLs and inline code with more than the ref in it are left alone, and a file the session didn't touch is never linked; a link whose text is such a ref alone (github-pr's link to the PR diff) becomes a ref too, and its plain click still goes to the PR. A plugin's refs on an answer (an `after_turn` hook's, see [Refs on the answer](hooks.md#refs-on-the-answer-display-only)) are paired with its links and text whatever the rows touched: they can link a file the session didn't touch, or an issue or a commit, and add their own actions to the ref's menu. A plugin tool's row carries the refs its `refs:` gives (see [Refs on a tool's row](plugins.md#refs-on-a-tools-row)): its title opens the first, and its `▾` menu adds the others as `<ref> · <action>` (the URL on hover); their URL actions work on a phone too. A ref with more than one target shows a small `▾` on hover: it opens a menu of them, in order **PR diff** (a link's), **Open in editor**, **Show in turn** and **Copy path**, and a plain click runs the first (a link's own, else the editor, else show in turn). **Show in turn** scrolls to the tool row that touched the file (looked for in the ref's own step, then its own turn, then the rows before it, then the nearest after it; there, the last one showing the ref's line, else the last one), opens the steps, the stage's steps and the row's diff (or the read showing the line) and flashes the row and the line; an answer's or a step's ref and an approval card's path have it, not a row's own title or lines. It needs no editor, so a viewer without one (a phone on the LAN) gets an answer's refs with **Show in turn** as their click; a row's title and diff lines stay plain text there. On a touch screen a tap opens the menu. A ref with a target is a tab stop: Enter runs its first target, ↓ opens the menu (↑/↓ move, Enter picks, Esc closes back to the ref). Diff and read lines have their click only. The info bar's id copies the full session id on click ("Session id copied"), the id every CLI command takes (`chi --attach ID`, `chi send ID`). A session whose prompt carried model notes has a `notes: deepseek` chip there (the names without `model_notes_`; the tooltip lists each with its scope and size; `session.prompt_notes` in `GET /api/sessions/:id`, the live worker's, else the session file's; see [Memory](memory.md#model-notes)). Its ⚙ chip, after the model, holds the session's thinking level, reasoning history and LLM context: `⚙` alone while the session follows the model for all three, else `⚙` and what the session set, in the accent colour (`⚙ think low · ctx stale,forget`; a phone shows ⚙ with a dot; the tooltip gives each value and its source). Its panel is the start page's ⚙ panel for this session: a Thinking row (`/thinking`), on a chat host a Reasoning row (the reasoning history, `/reasoning-history`), and a Context row with its Apply and budget fields (`/llm-context`); a tap runs that row's command at once in the worker (one reply in the conversation, as a typed one) and changes that field alone, the Context row's `default` resets the strategy, apply rule and budget (`/llm-context reset`), and a tap while a turn runs is queued for after it (the panel's note says so). `GET /api/sessions/:id`'s `session.thinking`, `session.reasoning_history` (null on a native host) and `session.llm_context` carry the values (the live worker's, else resolved from the session file), and a `command_ran` that changed them carries the new ones. After ⚙, the 🧰 chip names the session's toolkit: `🧰` alone on the configured default (`toolkit.default`, `session.toolkit_default`), `🧰 lean` on another (see [Toolkits](configuration.md#toolkits); `/toolkit` changes it). A `/thinking` or `/reasoning-history` change typed in the composer that restarts the prompt cache asks first: the reply bubble has an **Apply (restarts the cache)** button that sends its `--yes` line (the ⚙ panel sends that line itself; see [Changes that restart the prompt cache](configuration.md#changes-that-restart-the-prompt-cache)). It shows the context used (`ctx 42%`) and the last generation's decode speed (`87 tok/s`, `~64 tok/s` when estimated; see `/stats` in [cli.md](cli.md#session-commands)); hovering `ctx` there or on a session card lists the session's tokens in (summed over every request, with the cached share), out (with reasoning) and the cost when the provider reports one, for this session only (one estimated from a `hosts.<name>.models` price shows with `~`: `cost: ~$0.54 ($0.42 reported, ~$0.12 estimated)`); after a `/model` switch the info bar's tooltip adds a `per model:` row per run of turns on one model above those totals (`splash:qwen3-35b · 6 turns · 96.0k in / 9.0k out · ~$0.02`, a switch's prefill under its row: `└ switch prefill 58.0k uncached prompt ≈$0.01`; the timing's `model_segments`, replaced by each `generation_completed`'s; the session cards stay as they were), and right after the switch its ctx % is the new model's window's; and the memory indexes its prompt holds (`memory index: ~3.4k tokens in this session's prompt (system 2.0k, project 1.4k)`; see [Memory](memory.md#the-indexs-size)). The start page's model picker (bottom left of the composer, the chosen name `▾`) chooses the model a new session starts on, and a fresh chain link's (see [Session chains](#session-chains); there a pick shows as a `/model` command bubble in the link); it opens a search list over the conversation (↓ or a click; downward when the start page leaves no room above): an empty search shows the last 5 picks (Recent) and then each host's model ids A–Z under the host, the default host first (an id the host declares under `hosts.<name>.models` first, noted `config`, its tooltip `served by config (hosts.<name>.models)`; a host that failed to list its models keeps those ids, greyed and noted `host down`, still pickable; a remembered or default model stays chosen even then, greyed on the button); typed words must each match the host or the id (a substring, else for 3+ characters the letters in order, so `deepseek4.1 fla` finds `openrouter · deepseek/deepseek-v4.1-flash`), ⏎ picks, Esc/Tab close, a pick puts the focus in the message box: `GET /api/models` lists the hosts' models as chi spells them (`{default, models: [{name, host, id, configured?, unavailable?, sampling?, llm_context?}], warning?}`; `configured: true` marks an id declared under `hosts.<name>.models`, listed first under its host, `unavailable: true` one whose host failed to list its models; `sampling` is the model's configured request parameters as `/model` words them, the row's tooltip in the list; bare for the default host, `host:model` for the others, from the same cached lists as `/models`, a bounded wait, a host that is down noted in `warning`; `toolkits`: `{default, suggest, kits: [{name, description?}]}`, the start page's 🧰 list: the configured `toolkit.default`, `suggest` `on` only when a new session's first message may get a suggested kit (`toolkit.suggest.mode: on`, a System 1 host, two described kits; else `audit` or `off`), and the built-in and config kits a new session can start on, without `review`, `child`, `undecided`, a kit `groups:` refuses or one that doesn't resolve (a base that is a bundle kit), the default always listed; left out when it can't be read), and `POST /api/sessions` takes `model` (blank means the default). Beside it, ⚙ opens the new session's rarely used settings (thinking and LLM context, following each `GET /api/models` row's `thinking` and `llm_context`, and the review files; see [configuration.md](configuration.md#llm-context-a-sessions-own-strategy)), and 🧰 its toolkit: **Auto** (with `toolkit.suggest.mode: on`: the first message may get a suggested kit, else the default) or a kit from the payload's `toolkits`, sent as `POST /api/sessions`'s `toolkit` (see [configuration.md](configuration.md#toolkits)); a refused kit (`400 toolkit_refused`) is said in the list, opened again. What is set shows on the row as an accent chip (`think high`, `tools: lean`; a dot on ⚙ or 🧰 on a phone); each is for the next new session only, never remembered. The start page's first message goes as later ones do: `POST /api/sessions` with `idle: true` and `preview` (the message, which names the session until its turn is saved), then `POST /api/sessions/:id/turn`, so a failed first turn puts its prompt back in the composer too; a first line that is one of the new session's commands (`/model …`) goes to `POST /api/sessions/:id/command` instead, as later ones do. The browser remembers the last model picked; a running session's model is in the info bar and changes only with `/model`. In the composer a line is a command when it is `!…` or starts with one of the session's command names (its `commands` list; `/stats`, `/exit` and the other terminal words get the page's own reply); an unknown `/word` (`/usr/bin/env is missing`) goes to the model as a prompt, as in a terminal; a one-word `/word` no command answers (`/modle`) is not sent: the page shows `Unknown command /modle. Did you mean /model? /help lists the commands.` (the "Did you mean" part only when a name is close). A `POST /turn` (or a session's first `prompt`) that is one of the worker's commands runs as that command too (`202 {status, command_id, session_id}`), so `chi send`, `chi -p` and a page whose command list lags all get the command. ↑/↓ in the composer walk the prompt history the TUI's ↑ walks ([Persistent Prompt History](cli.md#persistent-prompt-history)): ↑ with the caret on the first line, ↓ from the last line while browsing, ↓ past the newest brings the draft back; `GET /api/history` returns `{entries: [...]}`, oldest first (the page fetches it on focus and after each send). The server records a sent line in the routes once the worker took it (`POST /turn` accepted, a `!command` through `POST /command` or as a session's first line); `"history": false` in the body keeps it out (an image-only send).
|
|
104
106
|
- Web notifications: when a session needs you while the tab is hidden or behind another window (a question or a guardrail approval, a plugin card with buttons during a turn such as check-in's, a failed turn, a turn done after 10 s or more; a delegated session only for its questions, a canceled turn never), the page title counts it, `(N) Chi`, until you come back to the tab. The bell at the right of the top bar also turns on OS notifications ("needs an answer", "needs approval", "needs you", "turn failed", "done in 42 s", under the session's first message; a click opens the session): its first click asks the browser for the permission, and the choice is kept per browser. Any session of the page's scope counts, not only the open one. What was already so when the page loaded never counts, and several chi tabs show one notification per event. A chi tab in front tells the others (a `BroadcastChannel`), so while you look at one, the ones behind neither notify nor count what it shows; coming back to a tab clears those events in the other tabs' titles too. The hub's `session` frames carry what this needs: `pending_question` (`{id, kind}`, kind `question` or `approval`), `pending_card` (`{id, bundle}`: the running turn's card with actions, from `pending_card.json` that the worker keeps in the session's folder while one is open; a card without actions, such as loop-guard's, never counts) and `last_turn` (`{outcome, ended_at, seconds, origin}`, saved in the session's JSON as the engine ends each turn).
|
|
105
|
-
- The web frontend is a zero-build ES-module stack in `lib/samagotchi/web/public/`: `data.js` (retrieval, typed SSE `openStream` for a session and `openEvents` for the session list), `sessions_list.js` (the list as a pure reducer over `GET /api/events`: a snapshot replaces it, an upsert keeps a known card in place, a removal drops it; `families()` groups delegates under their parent), `families_view.js` (a parent's family chip, its rows and the strip's popover; the chip and rows as lit-html templates), `keep_focus.js` (lit reuses a list's nodes by position: a redraw keeps the focus on the same item by its `data-id` / `data-name`), `chains.js` (session chains: the links from `continues`, the cards folded into the latest link's, its `#N` chip and rows as lit-html templates, the info bar's ← → links, a refused continue, and the fresh-link rule), `notify.js` (which of those events needs the user, for the notifications), `app.js` (presentation/state; a session with no live stream gets one when its `session` event says `bridge_up`, after one re-read: `event_seq` starts over in each worker, so a dropped stream is never resumed with its old cursor), `bubbles.js` (the history's bubbles between the turns' rows: output chunks, end lines, every client's prompt bubbles by `enqueued_id` with their queued/steered badges, the idle recap, guardrail warnings, hooks' notices, plugins' steers, command and note bubbles; lit-html templates, put in the history with the sticky follow by `createBubbles`), `cards_place.js` (where plugin cards and a snapshot's notices go in the history: a card added or updated in place by its id, a running turn's into its step, a snapshot's each above the first turn after it, a finished turn's notice in its step's rows and its question resolved where it was asked; a card's action buttons), `format.js` (pure formatters such as `previewOf`), `plain_line.js` (markdown out of the plain one-line places: the stage headline, a closed step's title, an answered question card's kept-reply line), `prompt_history.js` (the composer's ↑/↓ over the shared prompt history), `commands.js` (session commands: which composer lines are commands, the page's own replies, a `command_ran`'s bubble, the page's command bubbles kept across a re-read), `composer.js` (where a composer line goes, `routeComposerLine`: /cut and /queue, the start page's own replies, a session command or `!cmd`, a typo hint, else a turn; and a session command sent from the composer or a chip), `delivery_line.js` (the composer's row above the text field in a session, always there so the composer keeps its height: the key hint while idle, and the delivery line while a turn runs: where a message typed now goes in, from the step's phase, clock and size, whether "cut in now" can land, and the queue link for a worker with the `delivery` feature, as a pure `deliveryLine`, its lit-html template and `createDeliveryControl`, which ticks it and keeps a choice armed from a link; see docs/cli.md, "Typing during a turn"), `restore.js` (a failed turn's prompt handed back into this tab's composer, before or after its `/turn` ack), `lists_view.js` (the session lists: the strip and its pill, all sessions with its search, count and select mode, their cards, the family and chain popovers; the cards, tile and pill as lit-html templates, drawn as new nodes each time, and the lists' orders as pure functions), `stream_handlers.js` (the open session's stream event handlers, by event type, over the page's views and hooks; a snapshot replays through them too), `stage_view.js` (the stage view: the running turn pinned above the composer, with Stop turn in its status row while it runs, then handed off into the history; its pure rules and texts in `stage_model.js`, its live slots (headline, now row, trail, ticks) in `stage_slots.js`, its cap and held height in `stage_frame.js`, the in-use watch that times the hand-off in `stage_watch.js`), `info_bar.js` (the session bar's info line as a lit-html template over a plain model, three groups with hairlines between them, on one line above a phone's width (the folder gives way first): the setup (id, status, model, the ⚙ and 🧰 chips, notes, the memory or working-set chip), the relations (chain links, the parent as `↑ <id>`, delegates, participants; only when there is one) and the telemetry (folder, ctx, speed, the session's time, worker badge)), `settings_chip.js` (the session bar's ⚙ chip and its panel over `settings_panel.js`: a tap runs that row's command, one field), `toolkit_chip.js` (the session bar's 🧰 chip: the kit against `toolkit.default`), `info_bar_model.js` (that model and the bar's buttons' states, built from the page's session state, its list and its in-flight continues and restarts (the restarting set is `version_notices.js`'s) as pure functions; `app.js`'s `updateInfoBar` applies them every second while a turn runs), `session_state.js` (what the page knows about the open session: its empty state, and `sessionStateFrom`, the fields a `GET /sessions/:id` payload sets), `refs.js` (refs: a kind and a target on the element, a plugin's ref data (label, http(s) URL actions) bound in a WeakMap by `bindRef`, the targets per kind, show in turn, one delegated set of click, key and hover listeners), `ref_menu.js` (a ref's `▾` and its menu), `ref_scan.js` (the `path:line` refs in an answer's or a step's text that name a file the session's rows touched), `answer_refs.js` (the refs a plugin attached to an answer, its `display_refs`: bound to the answer's bubble, paired with its links and text, bound with `bindRef`), `markdown_place.js` (where rendered markdown and its refs go: a text as markdown HTML, its `path:line` refs, a final answer's rendering), `images.js` (image chips in the composer: paste, drop and the image button, the upload before a turn, the thumbnails and the lightbox), `composer_grip.js` (the composer's grip and fold: the drag, tap and keys, the fold per visit), `composer_mount.js` (the composer mounted on a page's markup: the message box and its height, the image chips from a paste, a drop or the image button, the grip and fold, ↑/↓ over the prompt history and the keys; the page's own parts come in as hooks: what Enter and Send do, keys taken first, Esc, where the history comes from, the info bar's drop while folded, typing anywhere to open it; its styles, the card it sits in (`.composer-card`, its footer and its line above the text field) included, are the shared `composer.css`, linked after `tokens.css` by `index.html` and `participant.html`), `strip_grip.js` (the latest-sessions strip's grip, the composer grip's twin: hides and shows the strip), `strip_hidden.js` (the strip hidden or shown: the saved choice, the short window's own hide, the grip and the body's class), `review_history.js` (a participant's ↑/↓ list on the participant page: their own comments, in localStorage per grant, never the owner's `/api/history`; `participant.js` mounts `composer_mount.js` with it, no `/` list, no delivery choices, images off), `storage.js` (the page's per-browser choices in localStorage, guarded: a choice that can't be read or written is not remembered), `unqueue.js` (the × on a message queued for after the turn: takes it back, its text into an empty composer or a toast), `toasts.js` (the page's toast stack: a timer each, sticky ones until acted on, the same text reusing its item), `toast_place.js` (where the toast sits: above the composer card, the stage and an open model panel), `dock_reserve.js` (what floats over the history: the history's bottom reserve (`--dock-h`) at the composer card's and the showing stage's height, a reader at the end kept there, and the toast's place measured for `toast_place.js`), `notice_links.js` (a hook notice line's http(s) URLs as links), `start_page.js` (the start page's model picker, its ⚙ panel's and 🧰 list's choices for the next new session only and their override chips; a fresh chain link's picker and its `/model`), `start_settings.js` (the start page's ⚙ panel: thinking and LLM context as rows of segments, applied at once, the Apply and budget disclosure, the review files' view; the override chips' words and ⚙'s dot), `settings_panel.js` (the panel's rows as lit-html templates, shared: the segments, the disclosure, a hidden row's sent-anyway line, the review line; the caller passes its rows and applies the picks), `start_toolkit.js` (the start page's 🧰 list: Auto with suggest on, the kits, the default marked; a pick closes it; its override chip and dot), `session_actions.js` (Continue, Archive and its Undo, Delete and Stop, and the start page when the open session is gone), `send_turn.js` (the composer's send: a new session first on the start page, the route, the echo, the image upload, the `/turn` ack, a fast failure's restore and each error's place). Unit-tested via `npm test` (`spec/web/public/*.test.js`).
|
|
107
|
+
- The web frontend is a zero-build ES-module stack in `lib/samagotchi/web/public/`: `data.js` (retrieval, typed SSE `openStream` for a session and `openEvents` for the session list), `sessions_list.js` (the list as a pure reducer over `GET /api/events`: a snapshot replaces it, an upsert keeps a known card in place, a removal drops it; `families()` groups delegates under their parent), `families_view.js` (a parent's family chip, its rows and the strip's popover; the chip and rows as lit-html templates), `keep_focus.js` (lit reuses a list's nodes by position: a redraw keeps the focus on the same item by its `data-id` / `data-name`), `chains.js` (session chains: the links from `continues`, the cards folded into the latest link's, its `#N` chip and rows as lit-html templates, the info bar's ← → links, a refused continue, and the fresh-link rule), `notify.js` (which of those events needs the user, for the notifications), `app.js` (presentation/state; a session with no live stream gets one when its `session` event says `bridge_up`, after one re-read: `event_seq` starts over in each worker, so a dropped stream is never resumed with its old cursor), `bubbles.js` (the history's bubbles between the turns' rows: output chunks, end lines, every client's prompt bubbles by `enqueued_id` with their queued/steered badges, the idle recap, guardrail warnings, hooks' notices, plugins' steers, command and note bubbles; lit-html templates, put in the history with the sticky follow by `createBubbles`), `cards_place.js` (where plugin cards and a snapshot's notices go in the history: a card added or updated in place by its id, a running turn's into its step, a snapshot's each above the first turn after it, a finished turn's notice in its step's rows and its question resolved where it was asked; a card's action buttons), `format.js` (pure formatters such as `previewOf`), `plain_line.js` (markdown out of the plain one-line places: the stage headline, a closed step's title, an answered question card's kept-reply line), `prompt_history.js` (the composer's ↑/↓ over the shared prompt history), `commands.js` (session commands: which composer lines are commands, the page's own replies, a `command_ran`'s bubble, the page's command bubbles kept across a re-read), `composer.js` (where a composer line goes, `routeComposerLine`: /cut and /queue, the start page's own replies, a session command or `!cmd`, a typo hint, else a turn; and a session command sent from the composer or a chip), `delivery_line.js` (the composer's row above the text field in a session, always there so the composer keeps its height (on a phone no row: the line lies over the session bar's left while a turn runs and you type or have a choice armed): the key hint while idle, and the delivery line while a turn runs: where a message typed now goes in, from the step's phase, clock and size, whether "cut in now" can land, and the queue link for a worker with the `delivery` feature, as a pure `deliveryLine`, its lit-html template and `createDeliveryControl`, which ticks it and keeps a choice armed from a link; see docs/cli.md, "Typing during a turn"), `restore.js` (a failed turn's prompt handed back into this tab's composer, before or after its `/turn` ack), `lists_view.js` (the session lists: the strip and its pill, all sessions with its search, count and select mode, their cards, the family and chain popovers; the cards, tile and pill as lit-html templates, drawn as new nodes each time, and the lists' orders as pure functions), `stream_handlers.js` (the open session's stream event handlers, by event type, over the page's views and hooks; a snapshot replays through them too), `stage_view.js` (the stage view: the running turn pinned above the composer, with Stop turn in its status row while it runs, then handed off into the history; its pure rules and texts in `stage_model.js`, its live slots (headline, now row, trail, ticks) in `stage_slots.js`, its cap and held height in `stage_frame.js`, the in-use watch that times the hand-off in `stage_watch.js`), `info_bar.js` (the session bar's info line as a lit-html template over a plain model, three groups with hairlines between them, on one line above a phone's width (the folder gives way first): the setup (id, status, model, the ⚙ and 🧰 chips, notes, the memory or working-set chip), the relations (chain links, the parent as `↑ <id>`, delegates, participants; only when there is one) and the telemetry (folder, ctx, speed, the session's time, worker badge)), `settings_chip.js` (the session bar's ⚙ chip and its panel over `settings_panel.js`: a tap runs that row's command, one field), `toolkit_chip.js` (the session bar's 🧰 chip: the kit against `toolkit.default`), `info_bar_model.js` (that model and the bar's buttons' states, built from the page's session state, its list and its in-flight continues and restarts (the restarting set is `version_notices.js`'s) as pure functions; `app.js`'s `updateInfoBar` applies them every second while a turn runs), `session_state.js` (what the page knows about the open session: its empty state, and `sessionStateFrom`, the fields a `GET /sessions/:id` payload sets), `refs.js` (refs: a kind and a target on the element, a plugin's ref data (label, http(s) URL actions) bound in a WeakMap by `bindRef`, the targets per kind, show in turn, one delegated set of click, key and hover listeners), `ref_menu.js` (a ref's `▾` and its menu), `ref_scan.js` (the `path:line` refs in an answer's or a step's text that name a file the session's rows touched), `answer_refs.js` (the refs a plugin attached to an answer, its `display_refs`: bound to the answer's bubble, paired with its links and text, bound with `bindRef`), `markdown_place.js` (where rendered markdown and its refs go: a text as markdown HTML, its `path:line` refs, a final answer's rendering), `images.js` (image chips in the composer: paste, drop and the image button, the upload before a turn, the thumbnails and the lightbox), `composer_grip.js` (the composer's grip and fold: the drag, tap and keys, the fold per visit), `composer_mount.js` (the composer mounted on a page's markup: the message box and its height, the image chips from a paste, a drop or the image button, the grip and fold, ↑/↓ over the prompt history and the keys; the page's own parts come in as hooks: what Enter and Send do, keys taken first, Esc, where the history comes from, the info bar's drop while folded, typing anywhere to open it; its styles, the card it sits in (`.composer-card`, its footer and its line above the text field) included, are the shared `composer.css`, linked after `tokens.css` by `index.html` and `participant.html`), `strip_grip.js` (the latest-sessions strip's grip, the composer grip's twin: hides and shows the strip), `strip_hidden.js` (the strip hidden or shown: the saved choice, the short window's own hide, the grip and the body's class), `review_history.js` (a participant's ↑/↓ list on the participant page: their own comments, in localStorage per grant, never the owner's `/api/history`; `participant.js` mounts `composer_mount.js` with it, no `/` list, no delivery choices, images off), `storage.js` (the page's per-browser choices in localStorage, guarded: a choice that can't be read or written is not remembered), `unqueue.js` (the × on a message queued for after the turn: takes it back, its text into an empty composer or a toast), `toasts.js` (the page's toast stack: a timer each, sticky ones until acted on, the same text reusing its item), `toast_place.js` (where the toast sits: above the composer card, the stage and an open model panel), `dock_reserve.js` (what floats over the history: the history's bottom reserve (`--dock-h`) at the composer card's and the showing stage's height, a reader at the end kept there, and the toast's place measured for `toast_place.js`), `notice_links.js` (a hook notice line's http(s) URLs as links), `start_page.js` (the start page's model picker, its ⚙ panel's and 🧰 list's choices for the next new session only and their override chips; a fresh chain link's picker and its `/model`), `start_settings.js` (the start page's ⚙ panel: thinking and LLM context as rows of segments, applied at once, the Apply and budget disclosure, the review files' view; the override chips' words and ⚙'s dot), `settings_panel.js` (the panel's rows as lit-html templates, shared: the segments, the disclosure, a hidden row's sent-anyway line, the review line; the caller passes its rows and applies the picks), `start_toolkit.js` (the start page's 🧰 list: Auto with suggest on, the kits, the default marked; a pick closes it; its override chip and dot), `session_actions.js` (Continue, Archive and its Undo, Delete and Stop, and the start page when the open session is gone), `send_turn.js` (the composer's send: a new session first on the start page, the route, the echo, the image upload, the `/turn` ack, a fast failure's restore and each error's place). Unit-tested via `npm test` (`spec/web/public/*.test.js`).
|
|
106
108
|
- Selecting a session in the web UI is read-only: `GET /api/sessions/:id` never spawns a worker (it reads a live worker's snapshot when one runs, else the session file). A prompt (`POST /turn`) or a command (`POST /command`) wakes the worker, and `/stream` briefly waits for a freshly-spawned bridge before answering. A caught-up SSE reconnect holds the stream open; `reset` markers are only sent for reconnects behind the ring window, or with a cursor from another worker (event ids are `<event_seq>-<epoch>`, one epoch per worker).
|
|
107
109
|
- The web session page's message box folds away for room to read. Drag the grip on its top edge (the pill that shows on hover; always on a phone) down, past the box by 32 px: the pill turns accent while releasing would hide it, and on release the box folds and the info bar stays as the page's bottom edge. The grip stays as a handle on the info bar's top edge, drawn always: pull it up (8 px opens it, and the box follows the pointer in the same gesture), click or tap it (opens it and focuses the box), or just type on the page (the key lands in the box) to bring it back; Enter or Space on the focused grip folds or opens too. A draft (text or images, which folding never clears) colours the handle with the accent, a session waiting on you with the attention colour; its tooltip says so. Stop turn isn't the message box's: it sits in the running turn's stage, at the right edge of its status row beside the fold caret (collapsed stage or not), while the turn runs, and goes when the turn ends A turn the page knows runs but has nothing of to draw (a reload whose session payload carries no current turn) shows that status row alone, `running` and Stop turn. The fold is remembered per browser (`chi_composer_collapsed`), an archived session opens folded for the visit, and opening it there, like the page opening it itself (a restored line, a quote, continue →'s opener), is for that visit only. The fold keeps the height the grip set (`chi_composer_floor`): the box opens again at the height it had, and only a double-click on the grip forgets it. That height never takes more than half of the window the box is drawn in: a floor saved in a bigger window is held to that half in a smaller one (a rotated phone, a resized window, another device on the same origin), and the saved floor itself stays, so the height comes back when the room does. A click on the expanded grip hides the box as well: it folds 250 ms after the press, so a second click inside that window is read as a double-click and resets the height instead (a drag, Enter or Space act at once, and a drag after a click takes the wait back). The start page's grip only resizes.
|
|
108
110
|
|
|
@@ -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
|
|
|
@@ -524,7 +526,7 @@ mise.toml pins Ruby 3.4 gets that `ruby`, `gem` and `bundle` in its tools while
|
|
|
524
526
|
|
|
525
527
|
The `delegate` tool hands a task to a **child session**: an ordinary chi session in a worker of its own, started in the parent's `working_directory` with the task, verbatim, as its first user message, on the parent's model unless the call names one (`model:` takes a name or an alias, resolved as `--model` is; an unknown host comes back as the tool's `Error:` line; an id the host's saved model list doesn't have starts the child with a `Warning: host 'h' doesn't list model 'x' (did you mean: …?)` line in the result). Children run in parallel and only their **final reply** comes back to the parent: the child's newest `output/<timestamp>.txt` file, which the worker writes at the end of each turn that produced visible text, cut head-and-tail above 64 KB (`DelegateWait.cut`); a reply longer than `max_tool_output_chars` keeps its start and its end (the conclusion), with a gap line naming that `output/` file, where the whole reply is (`ToolOutputCut`'s `:head_tail_ref`; see [Tool output guardrails](internals/tool-output-limits.md#the-runners-cut-max_tool_output_chars)). Nothing of the child's trace enters the parent's context. Nothing is hidden: a child shows in `chi sessions list` (`↳ <parent>`), the web (folded into its parent's card on the strip and in all sessions, whose `▸ N delegates` chip lists the delegates at any depth, see Web UI above; a card of its own with a `↳` chip when its parent isn't listed; `↑ <parent id>` in its info bar, its tooltip `delegated by session …`; the parent's info bar carries a `⑂ N` chip counting its delegates, with how many run, wait, are done, failed, stopped or idle in the tooltip and the waiting ones named in the attention colour; a click opens all sessions), the terminal's status row (a parent's `⑂ 2 running · 1 waiting`, see [Status Line](cli.md#status-line)) and the `list_sessions` tool (`child`; the parent shows as `parent` in the child's own list); the user can `chi --attach <child id>` and steer it mid-run, and `chi send` and `send_note` reach it like any session.
|
|
526
528
|
|
|
527
|
-
- `delegate(task, model:, session:, cwd:, wait:, timeout:)`: starts a child and, by default, waits for its reply. `wait: false` is the usual way for work that takes a while, several children side by side, or to keep talking with the user: it returns at once, the parent ends its turn or works on, and the reply comes back by itself as a *delegate report* (below), in a turn of its own if the parent is idle. The tool descriptions tell the model so, and to wait (`wait: true`, `delegate_result`) only when its turn can't go on without the reply. `timeout`, default 600 s, leaves a slow child running; 0 checks once without waiting. With `session:` (a child's id or prefix) the task goes to that child as a follow-up instead, delivered like `chi send` (client id `delegate:<parent short id>`, shown as `delegate>` in the child's UIs); only this session's children take one. The wait (`wait: true`, a later `delegate_result`) and the delegate report are for the reply of the child's turn the follow-up went to (`turn` in `delegates.json` is the follow-up's own id, set when the child's worker names `turn_ids`): the turn of its own it runs, or the running turn whose drain merges it as a steer (the drain's `input/merged/` record says which
|
|
529
|
+
- `delegate(task, model:, session:, cwd:, wait:, timeout:)`: starts a child and, by default, waits for its reply. `wait: false` is the usual way for work that takes a while, several children side by side, or to keep talking with the user: it returns at once, the parent ends its turn or works on, and the reply comes back by itself as a *delegate report* (below), in a turn of its own if the parent is idle. The tool descriptions tell the model so, and to wait (`wait: true`, `delegate_result`) only when its turn can't go on without the reply. `timeout`, default 600 s, leaves a slow child running; 0 checks once without waiting. With `session:` (a child's id or prefix) the task goes to that child as a follow-up instead, delivered like `chi send` (client id `delegate:<parent short id>`, shown as `delegate>` in the child's UIs); only this session's children take one. The wait (`wait: true`, a later `delegate_result`) and the delegate report are for the reply of the child's turn the follow-up went to (`turn` in `delegates.json` is the follow-up's own id, set when the child's worker names `turn_ids`): the turn of its own it runs, or the running turn whose drain merges it as a steer (the drain's `input/merged/` record says which), not a newer reply of a turn queued behind it. A follow-up the running turn ended without taking runs as its own turn and gets that turn's reply. A child on its first turn, or with an older worker, gives its next reply, as before.
|
|
528
530
|
- `cwd:` starts the child in another folder of the parent's project (a repository or a marked folder): a linked worktree (`git worktree add ../<repo>-<task> -b <branch>`, which the model runs with `execute` first, under guardrails; chi runs no git here) or a subfolder; a relative path is taken from the parent's folder. The folder must exist, have the parent's project root (the same common git dir, `MemoryPaths.project_root`) and be in a work tree: a git dir (`.git`, `.git/objects`, a bare layout's `.bare`) or a bare layout's container is refused (`git rev-parse --is-inside-work-tree`, read-only, decides). In a marked project the folder must have the parent's project root too (so a nested repository or marked project is refused); outside both only a subfolder of the parent's folder is allowed. Otherwise the tool returns `Error: cwd must be a folder of this session's project …` or `… is not in a work tree …`. A follow-up (`session:`) refuses `cwd:`: the child keeps its folder. The child's guardrails measure from its own worktree, and project memories, `list_sessions` and the web's project are the same as the parent's. With no `cwd:` and a task that names another checkout of the same repository (a path in the task belonging to a linked worktree, read from the files with `Guardrails::GitInfo.checkouts`, no git process), the result carries `Warning: this child runs in <folder>, but its task names <checkout>. If it should work there, stop it (chi sessions stop <id>) and call delegate again without session, with cwd: <checkout>.` One line however many are named; nothing for a path of the child's own checkout, a folder that isn't one, a path with spaces, or the main checkout when the child runs in a linked worktree of it (the work belongs in the worktree, so naming a main-checkout file is not a forgotten `cwd:`). The child starts as it would anyway, and with `wait: true` (the default) the line comes after the child ran, so it only helps with `wait: false`. A `Warning:` for an unknown model id comes first, then this one. `Log.info(:worker, "delegate_other_checkout", parent:)` records each line.
|
|
529
531
|
- `delegate_result(session:, timeout:)`: waits for a child's next reply: the one named, or the newest running child (`timeout` as for `delegate`: 0 checks once and returns at once). The reply comes back once; a later call waits for the next one. After `wait: false` it isn't needed: the report brings the reply.
|
|
530
532
|
- A wait also ends early when a person's message waits for the parent's turn's next step (the `task_wait` rule: `Engine#input_waiting?`, `SessionInbox.steer_waiting?`, never in a participant's turn): `ReplyWait`'s `message_waiting:` probe gives `:message_waiting`, checked after every outcome the child can arrive at (a reply, a question, an end, a gone worker) and a cancel, before the deadline, and the result says `no reply yet: a message from the user is waiting; the child keeps running. Read the message first.` with the same last line as a timeout's. The child is never touched, the cursor doesn't move (the reply still comes, as a report or at the next `delegate_result`), a relayed approval's outcome line stays in the result, and a reserved report reads as for a timeout. A delegate child's report doesn't end a wait. This holds for `delegate`'s own wait too (both go through `DelegateWait`).
|
data/docs/testing.md
CHANGED
|
@@ -148,9 +148,40 @@ 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
|
|
152
|
-
|
|
153
|
-
|
|
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. 0.165.0's approvals (a list) are
|
|
162
|
+
also read as recorded and wrapped in a versioned store, the shape a later chi writes.
|
|
163
|
+
A corpus recorded after 0.165.0 also holds `wire/`: a worker's replies to `GET state`, `snapshot` (after a turn, and
|
|
164
|
+
mid-turn with a prompt queued behind it) and `tail`, each `{route, status, body}`, and the session file it saved,
|
|
165
|
+
recorded from a real Engine and Bridge (`script/release/compat_wire.rb`, `CompatWire`: a scripted kernel, read over the
|
|
166
|
+
Bridge's HTTP with its secret). `spec/compat/wire_readers_spec.rb` serves them as recorded through a `BridgeClient`
|
|
167
|
+
(an unrecorded route is an older worker's 404) to today's clients: chi web's show and its `?tail=1`, `?cards=1`,
|
|
168
|
+
`?timing=1` reads, the working set read, `BridgeClient#event_seq`, the attached terminal's `/stats` fallback and
|
|
169
|
+
`ctx.sessions.read`; like `readers_spec`, one example reads the newest previous release's (skipped while that has no
|
|
170
|
+
`wire/`), one a recording made now. SSE frames aren't recorded (the stream's own specs pin them); the JS page's reads of
|
|
171
|
+
these replies are a follow-up. `spec/release/compat_wire_spec.rb` checks the recorder (what `normalise` pins, and the
|
|
172
|
+
two-recordings guard).
|
|
173
|
+
A second example reads a corpus the writer records now, so a writer change that
|
|
174
|
+
today's readers can't read goes red before the release. `rake
|
|
175
|
+
release:bump[X.Y.Z]` writes `spec/compat/X.Y.Z/` using the current writers
|
|
176
|
+
(`ReleaseTools.write_compat_corpus!`); commit those small samples with the
|
|
177
|
+
release so the next version exercises N-1.
|
|
178
|
+
|
|
179
|
+
Compat shims (code kept only for another chi version's data or protocol) are
|
|
180
|
+
registered in `Compat::SHIMS` (`lib/samagotchi/compat.rb`): an id, the release
|
|
181
|
+
that added it, `remove_after` (nil: the owner hasn't dated it) and its files,
|
|
182
|
+
each Ruby one naming it in a comment (`compat shim <id>`). `spec/compat_spec.rb`
|
|
183
|
+
fails once `Samagotchi::VERSION` passes a shim's `remove_after`, naming it:
|
|
184
|
+
remove the shim, or move its date with the owner's OK. A new shim gets a row.
|
|
154
185
|
|
|
155
186
|
## Levels
|
|
156
187
|
|
|
@@ -411,7 +442,9 @@ tools. Then come the other name matches (a spec named after several changed file
|
|
|
411
442
|
`toolkit.rb`; then one beside the file, so `plugin/context.rb` picks `spec/samagotchi/plugin/*context*` before
|
|
412
443
|
`spec/guardrails/context_spec.rb`), then the specs that name a method the change touches (the innermost `def` around a
|
|
413
444
|
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
|
|
445
|
+
`call`… and `Object`'s or `Enumerable`'s methods skip; one that names the changed file's class too comes first), then
|
|
446
|
+
the specs that name a changed file's class, then the specs that name only the method (often another class's
|
|
447
|
+
`deliver`, which would crowd the class's own specs past the cap). The method tier
|
|
415
448
|
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
449
|
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
450
|
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
|
-
|
|
109
|
-
|
|
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
|
-
|
|
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,
|
|
141
|
-
#
|
|
142
|
-
#
|
|
143
|
-
#
|
|
144
|
-
#
|
|
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
|
|
211
|
-
#
|
|
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
|
data/lib/samagotchi/bridge.rb
CHANGED
|
@@ -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.
|
|
1405
|
-
|
|
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,
|
data/lib/samagotchi/chi_home.rb
CHANGED
|
@@ -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(
|
|
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
|