samagotchi 0.175.0 → 0.177.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +50 -1
  3. data/bin/chi +1 -0
  4. data/docs/architecture.md +1 -1
  5. data/docs/cli.md +11 -4
  6. data/docs/configuration.md +1 -0
  7. data/docs/internals/bridge.md +2 -2
  8. data/docs/internals/engine.md +2 -2
  9. data/docs/internals/participants.md +13 -6
  10. data/docs/internals/prompt-caching.md +3 -0
  11. data/docs/internals/web-frontend.md +38 -11
  12. data/docs/internals/working-set.md +77 -6
  13. data/docs/sessions.md +3 -2
  14. data/lib/samagotchi/bridge.rb +11 -4
  15. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  16. data/lib/samagotchi/config.rb +3 -0
  17. data/lib/samagotchi/engine/models.rb +11 -0
  18. data/lib/samagotchi/engine/session.rb +9 -0
  19. data/lib/samagotchi/engine.rb +1 -0
  20. data/lib/samagotchi/engine_snapshots.rb +3 -0
  21. data/lib/samagotchi/participant_uploads.rb +14 -1
  22. data/lib/samagotchi/prompt_part.rb +66 -0
  23. data/lib/samagotchi/session.rb +10 -1
  24. data/lib/samagotchi/system_prompt.rb +191 -12
  25. data/lib/samagotchi/version.rb +1 -1
  26. data/lib/samagotchi/web/app.rb +15 -2
  27. data/lib/samagotchi/web/participant_images.rb +16 -12
  28. data/lib/samagotchi/web/participant_show.rb +1 -1
  29. data/lib/samagotchi/web/participant_view.rb +27 -1
  30. data/lib/samagotchi/web/public/app.js +7 -2
  31. data/lib/samagotchi/web/public/composer_fold.js +3 -1
  32. data/lib/samagotchi/web/public/composer_grip.js +18 -10
  33. data/lib/samagotchi/web/public/composer_mount.js +17 -6
  34. data/lib/samagotchi/web/public/ctx_tokens.js +33 -0
  35. data/lib/samagotchi/web/public/index.html +43 -9
  36. data/lib/samagotchi/web/public/restore.js +3 -1
  37. data/lib/samagotchi/web/public/session_fields.js +10 -4
  38. data/lib/samagotchi/web/public/session_prefs.js +92 -0
  39. data/lib/samagotchi/web/public/session_state.js +14 -1
  40. data/lib/samagotchi/web/public/session_store.js +1 -1
  41. data/lib/samagotchi/web/public/session_sync.js +3 -0
  42. data/lib/samagotchi/web/public/session_view.js +33 -3
  43. data/lib/samagotchi/web/public/stage_asking.js +20 -11
  44. data/lib/samagotchi/web/public/stage_cloud.js +3 -2
  45. data/lib/samagotchi/web/public/stage_missing.js +3 -5
  46. data/lib/samagotchi/web/public/stage_model.js +2 -1
  47. data/lib/samagotchi/web/public/stage_view.js +6 -1
  48. data/lib/samagotchi/web/public/stage_view_memory.js +76 -0
  49. data/lib/samagotchi/web/public/stream_handlers.js +10 -5
  50. data/lib/samagotchi/web/public/tokens.css +2 -2
  51. data/lib/samagotchi/web/public/turn_events.js +1 -1
  52. data/lib/samagotchi/web/public/working_set.js +51 -7
  53. data/lib/samagotchi/web/public/working_set_rail.js +22 -7
  54. data/lib/samagotchi/web/public/working_set_view.js +188 -58
  55. data/lib/samagotchi/web/public/ws_reader.js +2 -0
  56. data/lib/samagotchi/web/public/ws_sections.js +251 -0
  57. data/lib/samagotchi/web/server.rb +6 -2
  58. data/lib/samagotchi/web/session_show.rb +13 -2
  59. data/lib/samagotchi/worker/child_side.rb +123 -0
  60. data/lib/samagotchi/worker/command_queue.rb +350 -0
  61. data/lib/samagotchi/worker/leave.rb +286 -0
  62. data/lib/samagotchi/worker/scratch.rb +99 -0
  63. data/lib/samagotchi/worker/signal_grace.rb +96 -0
  64. data/lib/samagotchi/worker/startup.rb +92 -0
  65. data/lib/samagotchi/worker/wake_turns.rb +190 -0
  66. data/lib/samagotchi/worker.rb +25 -1065
  67. data/lib/samagotchi/worker_exit_claim.rb +12 -0
  68. data/lib/samagotchi/working_set.rb +32 -4
  69. data/lib/samagotchi/working_set_command.rb +3 -2
  70. data/lib/samagotchi/working_set_steer.rb +21 -3
  71. metadata +13 -1
data/docs/sessions.md CHANGED
@@ -6,7 +6,7 @@ Sessions are plain files — no DB. Each session is `~/.local/state/samagotchi/s
6
6
 
7
7
  **Verify verdicts:** a web Verify turn stamps its opening user message with `verify: {turn_id, quote}` (the selected source turn and quote; metadata only, never added to the prompt). When that turn completes and the final assistant reply's last non-empty line is a valid `Verdict: confirmed|refuted|unclear — <reason>`, the session file appends `{anchor: {turn_id, quote}, verdict, reason, by, check_turn_id, at}` to its optional `verdicts` array. `by` is the turn's author (nil for the owner), `check_turn_id` names the Verify turn, and `at` is its timestamp. The array is append-only; older files without it have no saved verdicts. An `unclear` verdict can be checked again by **Verify fresh** (a delegate child that gets only the claim; see *Delegating*): its verdict is appended to the parent's `verdicts` with `fresh: true`, `of` (the verdict it checked again) and `child_id`, from the parent's `fresh_verdicts/` dir, which its worker takes between turns. Verdicts are display state: none enters a prompt.
8
8
 
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`). A participant's Revise is theirs only (`ParticipantRevise`, from the authors the server stamped): the answer to their own message (not a Verify turn's), with only their own turn openings after it (an owner's `!` line, which they never see, counts for nothing). chi web checks it at the send against the live worker's snapshot (403 `revise_not_own`, the same for a missing turn; 409 `revise_overtaken`; 409 `revise_unavailable` for a live worker without the `participant_revise` feature), and the worker checks it again at the stamp, up to the Revise turn itself. A Revise someone else's turn overtook after the send silently becomes a plain turn: it runs and answers, but nothing folds, no stack is drawn and neither they nor the owner get a notice; only a `revise_anchor_rejected` log line (reason `overtaken` or `not_own`) records it. It isn't refused at the start because a participant gets no `prompt_restored`, so their text would be lost. A delivery to a live worker without `participant_revise` is refused too (`SessionManager::Delivery`, 409 `revise_unavailable` in their words). The owner's Revise is unchanged, of anyone's answer. Both anchors travel as one `TurnAnchors` inside chi; on the wire and in an input file each keeps its own key (`verify`, `revises`).
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`). A participant's Revise is theirs only (`ParticipantRevise`, from the authors the server stamped): the answer to their own message (not a Verify turn's), with only their own turn openings after it (an owner's `!` line, which they never see, counts for nothing). chi web checks it at the send against the live worker's snapshot (403 `revise_not_own`, the same for a missing turn; 409 `revise_overtaken`; 409 `revise_unavailable` for a live worker without the `participant_revise` feature), and the worker checks it again at the stamp, up to the Revise turn itself. A Revise someone else's turn overtook after the send silently becomes a plain turn: it runs and answers, but nothing folds, no stack is drawn and neither they nor the owner get a notice; only a `revise_anchor_rejected` log line (reason `overtaken` or `not_own`) records it. It isn't refused at the start (a turn can overtake it after the send). A delivery to a live worker without `participant_revise` is refused too (`SessionManager::Delivery`, 409 `revise_unavailable` in their words). The owner's Revise is unchanged, of anyone's answer. 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
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, one with images or one whose author isn't the running turn's (a participant's goes only into their own turn, and a participant's turn takes nobody else's: `SessionInbox.turn_end_data?`): 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?`; in a participant's turn only their own line): 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
 
@@ -106,7 +106,7 @@ chi sessions clean --dry-run --days 7 # test sessions older than 7 da
106
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).
107
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`), `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), `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 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 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`).
108
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).
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.
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 each session's own, remembered per browser (`chi_composer_collapsed:<session>`: folding one session's box leaves the others' as they were), 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, also the session's own (`chi_composer_floor:<session>`; the start page's lasts until a reload): 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.
110
110
 
111
111
  **Test-session hygiene:**
112
112
 
@@ -141,6 +141,7 @@ chi sessions clean --dry-run --days 7 # test sessions older than 7 da
141
141
  | `project_id` | A marked project's id (its `.chi/project.yml`'s `id:`), saved beside `project_root`: the session's project context sources are keyed by it, so they follow a moved folder. Absent for any other project. | creation |
142
142
  | `preloaded_memory_names`, `muted_memory_names` | `--memory` and `--mute`, written before the worker starts so a respawn builds the same prompt; copied by a fork and a continue. A fork drops the reserved `system/delegated` memory so its `parent_id` does not make it a delegate; a continuation of a delegate child drops it because the new link is not a delegate. | creation |
143
143
  | `prompt_notes` | The model notes the system prompt carried at its last build (`[{name, scope, chars, digest}]`, see [Memory](memory.md#model-notes)). | the Engine, at each prompt build |
144
+ | `prompt_parts` | The sizes of the parts the system prompt was made of at its last build (`[{kind, label, chars, tokens, ref, scope?}]`: a `tools` part first, then one per memory, file and plugin section in prompt order, the indexes one per scope; tokens at `chars / 4`; no text). `scope` is a memory part's, `project` or `system` (identity `system`, a model note its own, a preload the scope that answered its read); other parts and an older file leave it out, and the page then matches the part to the set's memory by name alone. A `/model` switch records `[]` until the next build. The web's head view lists them; an older file or worker has none and reads as `[]` (a missing field is the old case, the page draws without the part rows). | the Engine, at each prompt build |
144
145
  | `parent_id` | The session that delegated this one or forked it (`ctx.sessions.fork`); `null` otherwise. See [Delegating](#delegating). | `SessionManager.spawn_session`; `ChildMove` writes a `parent.json` beside it instead of this file |
145
146
  | `scratch` | A `chi scratch` session, deleted when its terminal leaves. | creation |
146
147
  | `last_turn` | How the last turn ended (`LastTurn`), for a parent's wait and the web's notifications. | the Engine, at a turn's end |
@@ -150,13 +150,16 @@ module Samagotchi
150
150
  # session, /exit --delete) or stop: ("all": stop everything the user
151
151
  # can stop first), returns nil when the worker will leave or
152
152
  # what keeps it up (a WorkerIdleExit::Hold: #reason, #tasks, #hint,
153
- # #holds); called with the event log held. Without one, POST /exit
153
+ # #holds); called with the event log held, and +exit_stopped+ is read
154
+ # there too, right after the accept. Without one, POST /exit
154
155
  # answers 501
155
156
  # @param exit_discards [#call, nil] after an exit the worker agreed to:
156
157
  # whether it will delete the session as empty (the 200 says
157
158
  # +discard+); without one the reply leaves the field out
158
159
  # @param exit_stopped [#call, nil] after a stop-all exit: what it stopped
159
- # (a HoldStop::Stopped) for the 200's +stopped+; nil leaves it out
160
+ # (a HoldStop::Stopped) for the 200's +stopped+; nil leaves it out. Read
161
+ # with the event log held, right after the accept (not for a restart),
162
+ # so a later exit's list is never this 200's
160
163
  # @param on_holds [#call, nil] what the user could stop in this worker
161
164
  # right now (WorkerIdleExit#stoppable_holds) for GET /holds; without
162
165
  # one that route answers 501
@@ -1169,11 +1172,16 @@ module Samagotchi
1169
1172
  deadline = fetched(parsed, "deadline")
1170
1173
  return BAD_DEADLINE unless deadline_valid?(deadline)
1171
1174
 
1175
+ stopped = nil
1172
1176
  hold = @engine.synchronize_events do
1173
1177
  raise IntakeClosed if stopped?
1174
1178
  next :expired if expired?("exit_expired", deadline, sid: session_id, client_id: client_id)
1175
1179
 
1176
- @on_exit_request.call(client_id, **options)
1180
+ accepted = @on_exit_request.call(client_id, **options)
1181
+ # Read here, right after the accept: every accept runs with the log
1182
+ # held, so no later exit's list can be the one this 200 carries.
1183
+ stopped = @exit_stopped&.call if accepted.nil? && !restart
1184
+ next accepted
1177
1185
  end
1178
1186
  return deadline_passed("exit request") if hold == :expired
1179
1187
 
@@ -1182,7 +1190,6 @@ module Samagotchi
1182
1190
 
1183
1191
  body = { status: "exiting", session_id: @session_id }
1184
1192
  body[:discard] = @exit_discards.call == true if @exit_discards
1185
- stopped = @exit_stopped&.call
1186
1193
  body[:stopped] = stopped.to_h if stopped
1187
1194
  return [{}, 200, body]
1188
1195
  end
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: samagotchi-system
3
- version: 0.175.0
3
+ version: 0.177.0
4
4
  scope: system
5
5
  description: Default system memories — identity, self map, config modification protocol, memory guide and the delegated-session rules
6
6
  files:
@@ -388,6 +388,9 @@ module Samagotchi
388
388
  # The stage view's working set (files, memories and URLs the turn brought into context): a rail in the stage, a
389
389
  # footprint under each finished turn and a "set N" chip in place of the mem chip; ?working_set=1|0 overrides it per page load.
390
390
  Entry.new(key: "web.working_set", yaml_path: %w[web working_set], type: :bool, default: true, expose: %i[env config cli], lifecycle: :web_start),
391
+ # Every session's stage starts folded to its status row in chi web (a session folded or unfolded by hand keeps
392
+ # its own, per browser: session_prefs.js); participants' pages too.
393
+ Entry.new(key: "web.stage_collapsed", yaml_path: %w[web stage_collapsed], type: :bool, default: false, expose: %i[env config cli], lifecycle: :web_start),
391
394
  # Opt-in: the page checks each finished turn against a reload of it (one full read per turn end) and chi web logs
392
395
  # reload_checked, with reload_mismatch and the kinds that differed (counts only, no content).
393
396
  Entry.new(key: "web.reload_check", yaml_path: %w[web reload_check], type: :bool, default: false, expose: %i[env config cli], lifecycle: :web_start),
@@ -81,6 +81,16 @@ module Samagotchi
81
81
  end
82
82
  private :record_prompt_notes
83
83
 
84
+ # Records +parts+ (PromptPart) on the session as the sizes of the
85
+ # prompt's parts; saved with it. A switch records [] (the old model's
86
+ # parts are not the new one's; the next build records its own; a build
87
+ # in flight on another thread may still record the old ones, as
88
+ # prompt_notes may).
89
+ def record_prompt_parts(parts)
90
+ @session.prompt_parts = Array(parts) if @session
91
+ end
92
+ private :record_prompt_parts
93
+
84
94
  # A failed turn's one line (the error's #summary). A host's failure
85
95
  # under an alias says what the alias became (HostRegistry#alias_note):
86
96
  # "host main" alone doesn't tell --model splash's user it was splash.
@@ -174,6 +184,7 @@ module Samagotchi
174
184
  # The notes the new model's prompt loads at its next build, so /model,
175
185
  # /stats and the web name them before the next turn does.
176
186
  record_prompt_notes(model_notes) if @session
187
+ record_prompt_parts([])
177
188
  sync_kernel_client!
178
189
  @client.invalidate_context_window!
179
190
  @metrics.forget_model_reports!
@@ -22,6 +22,13 @@ module Samagotchi
22
22
  @muted_memory_names.dup
23
23
  end
24
24
 
25
+ # @return [Array<String>] sorted, deduped names the prompt carries or
26
+ # will carry on a fresh session
27
+ def prompt_memory_names
28
+ names = Array(@prompt_builder.prompt_memory_names) + Array(prompt_notes).map(&:name)
29
+ names.map { |name| name.to_s.strip }.reject(&:empty?).uniq.sort
30
+ end
31
+
25
32
  # @return [Array<String>] the names the session preloads (config baseline
26
33
  # + --memory, minus mutes), known before the prompt is built, unlike
27
34
  # #activated_memory_names
@@ -72,6 +79,8 @@ module Samagotchi
72
79
  @metrics.memory_index = @prompt_builder.memory_index
73
80
  # The model notes it carries: the session records them (/stats, /model, the web).
74
81
  record_prompt_notes(@prompt_builder.prompt_notes)
82
+ # And the sizes of its parts (PromptPart), for the web's head view.
83
+ record_prompt_parts(@prompt_builder.prompt_parts)
75
84
  prompt
76
85
  end
77
86
 
@@ -95,6 +95,7 @@ require_relative "model_binding"
95
95
  require_relative "model_overlay"
96
96
  require_relative "model_notes"
97
97
  require_relative "prompt_note"
98
+ require_relative "prompt_part"
98
99
  require_relative "served_model"
99
100
  require_relative "image_store"
100
101
  require_relative "vision_context"
@@ -124,6 +124,8 @@ module Samagotchi
124
124
  # :used_memory_names [Array<String>] deduped memory names active this session
125
125
  # :prompt_notes [Array<Hash>] the model notes the prompt carried
126
126
  # ({name:, scope:, chars:, digest:}; #prompt_notes)
127
+ # :prompt_parts [Array<Hash>] the sizes of the prompt's parts
128
+ # ({kind:, label:, chars:, tokens:, ref:, scope:?}; Session#prompt_parts)
127
129
  # :parent_id [String, nil] the session that delegated this one
128
130
  # :model_name [String] the model turns run on now (after /model)
129
131
  # :served_model, :served_model_for [String, nil] what a generation of
@@ -153,6 +155,7 @@ module Samagotchi
153
155
  preloaded_memory_names: preloaded_memory_names,
154
156
  muted_memory_names: muted.dup,
155
157
  prompt_notes: prompt_notes.map(&:to_h),
158
+ prompt_parts: Array(session&.prompt_parts).map(&:to_h),
156
159
  parent_id: session&.parent_id,
157
160
  title: session&.title,
158
161
  model_name: effective_model_ref,
@@ -36,6 +36,8 @@ module Samagotchi
36
36
  def owned?(file, grant_id) = entries.any? { |entry| entry.file == file && entry.grant_id == grant_id }
37
37
  end
38
38
  BROKEN = State.new(entries: [].freeze, attempts: {}.freeze, broken: true)
39
+ WARNED_UNREADABLE = Set.new
40
+ WARNED_UNREADABLE_MUTEX = Mutex.new
39
41
 
40
42
  module_function
41
43
 
@@ -55,10 +57,21 @@ module Samagotchi
55
57
 
56
58
  State.new(entries: entries, attempts: attempts.transform_values(&:to_i), broken: false)
57
59
  rescue JSON::ParserError, SystemCallError, TypeError, KeyError, NoMethodError => e
58
- Log.warn(:web, "participant_images_unreadable", file: path, msg: e.message)
60
+ warn_unreadable(path, e)
59
61
  BROKEN
60
62
  end
61
63
 
64
+ def warn_unreadable(path, error)
65
+ stat = begin
66
+ File.stat(path)
67
+ rescue SystemCallError
68
+ nil
69
+ end
70
+ key = [path, stat&.size, stat&.mtime]
71
+ first = WARNED_UNREADABLE_MUTEX.synchronize { WARNED_UNREADABLE.add?(key) }
72
+ Log.warn(:web, "participant_images_unreadable", file: path, msg: error.message) if first
73
+ end
74
+
62
75
  # Distinct files +grant_id+ uploaded; a broken record reads as at quota.
63
76
  def count(dir, grant_id) = read(dir).count(grant_id)
64
77
 
@@ -0,0 +1,66 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "token_usage"
4
+
5
+ module Samagotchi
6
+ # One part of a session's system prompt, as its size: what the session
7
+ # file's `prompt_parts` records at each prompt build and the web's head view
8
+ # draws (the text itself is not kept). kind: a SystemPrompt::KINDS word, or
9
+ # "tools" (the tool declarations, wherever the model gets them); label: what
10
+ # the row says ("AGENTS.md", "N declared"); chars: the part's length in the
11
+ # prompt (a multi-item section's headings and joins are in its first part,
12
+ # so a section's parts sum to its text); tokens: chars at TokenUsage's one
13
+ # ratio; ref: the bare memory name (identity, notes, preloads), the file
14
+ # path (agents, appended), "bundle/name" (plugins), the scope (indexes),
15
+ # else nil; scope: a memory part's scope, "project" or "system" (identity:
16
+ # system; a note: its own; a preload: the scope that answered), so the
17
+ # page tells a project x from a system x; nil for other kinds and in a
18
+ # file written before it (the page then matches by name alone).
19
+ PromptPart = Data.define(:kind, :label, :chars, :tokens, :ref, :scope) do
20
+ def initialize(kind:, label:, chars:, tokens:, ref: nil, scope: nil)
21
+ super
22
+ end
23
+
24
+ # A part of +chars+ characters, its tokens counted by the one ratio.
25
+ def self.build(kind:, label:, chars:, ref: nil, scope: nil)
26
+ new(kind: kind.to_s, label: label.to_s, chars: chars, tokens: tokens_for(chars), ref: ref&.to_s, scope: scope&.to_s)
27
+ end
28
+
29
+ # @return [Integer] the tokens +chars+ characters count as
30
+ def self.tokens_for(chars) = (chars / TokenUsage::CHARS_PER_TOKEN).ceil
31
+
32
+ # A saved or wire record (string or symbol keys); nil without a kind.
33
+ def self.from_h(raw)
34
+ return raw if raw.is_a?(PromptPart)
35
+ return nil unless raw.is_a?(Hash)
36
+
37
+ get = ->(key) { raw.key?(key.to_s) ? raw[key.to_s] : raw[key] }
38
+ kind = get.call(:kind).to_s.strip
39
+ return nil if kind.empty?
40
+
41
+ chars = get.call(:chars)
42
+ chars = chars.is_a?(Numeric) ? chars.to_i : 0
43
+ tokens = get.call(:tokens)
44
+ new(kind: kind, label: get.call(:label).to_s, chars: chars,
45
+ tokens: tokens.is_a?(Numeric) ? tokens.to_i : tokens_for(chars), ref: get.call(:ref)&.to_s,
46
+ scope: get.call(:scope)&.to_s)
47
+ end
48
+
49
+ # The records of a saved list (others dropped).
50
+ # @return [Array<PromptPart>]
51
+ def self.list(raw)
52
+ Array(raw).filter_map { |entry| from_h(entry) }
53
+ end
54
+
55
+ # The record (the wire's, the file's): without scope when it has none,
56
+ # so a part that has no scope reads as an older chi wrote it.
57
+ def to_h
58
+ hash = super
59
+ hash.delete(:scope) if scope.nil?
60
+ hash
61
+ end
62
+
63
+ # The session file's record (string keys).
64
+ def to_file = to_h.transform_keys(&:to_s)
65
+ end
66
+ end
@@ -17,6 +17,7 @@ require_relative "toolkit"
17
17
  require_relative "session_config"
18
18
  require_relative "session_setup"
19
19
  require_relative "prompt_note"
20
+ require_relative "prompt_part"
20
21
  require_relative "working_set_pin"
21
22
  require_relative "session_review"
22
23
  require_relative "session_field"
@@ -182,6 +183,10 @@ module Samagotchi
182
183
  # Engine at each build (a start, a resume's or a woken worker's first
183
184
  # turn, /model) and saved, so what a session ran with can be read later.
184
185
  SessionField.list("prompt_notes") { PromptNote },
186
+ # The sizes of the parts that prompt was made of (Array<PromptPart>:
187
+ # kind, label, chars, tokens, ref), recorded with prompt_notes; the web's
188
+ # head view lists them. An older file has none: [].
189
+ SessionField.list("prompt_parts") { PromptPart },
185
190
  # The session that delegated this one (the `delegate` tool) or that a
186
191
  # plugin forked it from (ctx.sessions.fork), else nil.
187
192
  # Set before the spawn and kept on respawns, like preloaded_memory_names.
@@ -314,13 +319,17 @@ module Samagotchi
314
319
 
315
320
  # The value objects' readers and writers: a writer reads its value as
316
321
  # its FIELDS row does (a file's Hash, the object itself; nil is none).
317
- attr_reader :prompt_notes, :pending_question, :last_turn, :interrupted_turn, :toolkit, :review, :verify_fresh,
322
+ attr_reader :prompt_notes, :prompt_parts, :pending_question, :last_turn, :interrupted_turn, :toolkit, :review, :verify_fresh,
318
323
  :working_set_pins
319
324
 
320
325
  def prompt_notes=(value)
321
326
  @prompt_notes = load_field("prompt_notes", value)
322
327
  end
323
328
 
329
+ def prompt_parts=(value)
330
+ @prompt_parts = load_field("prompt_parts", value)
331
+ end
332
+
324
333
  def pending_question=(value)
325
334
  @pending_question = load_field("pending_question", value)
326
335
  end