samagotchi 0.161.0 → 0.163.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 (39) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +41 -1
  3. data/docs/architecture.md +2 -2
  4. data/docs/cli.md +1 -1
  5. data/docs/configuration.md +1 -1
  6. data/docs/internals/block-renderers.md +3 -2
  7. data/docs/internals/bridge.md +85 -22
  8. data/docs/internals/inline-widgets.md +6 -3
  9. data/docs/internals/web-frontend.md +1 -1
  10. data/docs/memory.md +8 -2
  11. data/docs/sessions.md +1 -1
  12. data/docs/testing.md +13 -1
  13. data/lib/samagotchi/bridge/card_store.rb +23 -13
  14. data/lib/samagotchi/bridge/turn_accumulator.rb +7 -1
  15. data/lib/samagotchi/bridge/turn_drawings/synth.rb +559 -0
  16. data/lib/samagotchi/bridge/turn_drawings.rb +118 -7
  17. data/lib/samagotchi/bridge/turn_ranges.rb +175 -0
  18. data/lib/samagotchi/bridge.rb +35 -12
  19. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  20. data/lib/samagotchi/plugin/sessions.rb +8 -1
  21. data/lib/samagotchi/project_command.rb +74 -6
  22. data/lib/samagotchi/project_id_clash.rb +1 -1
  23. data/lib/samagotchi/project_subfolders.rb +188 -0
  24. data/lib/samagotchi/terminal_ui/join_replay.rb +36 -130
  25. data/lib/samagotchi/terminal_ui.rb +12 -1
  26. data/lib/samagotchi/version.rb +1 -1
  27. data/lib/samagotchi/web/message_display.rb +58 -37
  28. data/lib/samagotchi/web/public/app.js +8 -7
  29. data/lib/samagotchi/web/public/block_frame.js +5 -1
  30. data/lib/samagotchi/web/public/data.js +4 -6
  31. data/lib/samagotchi/web/public/reload_check.js +7 -4
  32. data/lib/samagotchi/web/public/time_gaps.js +1 -2
  33. data/lib/samagotchi/web/public/timing.js +52 -216
  34. data/lib/samagotchi/web/public/turn_block.js +46 -124
  35. data/lib/samagotchi/web/public/turn_html.js +3 -2
  36. data/lib/samagotchi/web/public/widget_walk.js +4 -2
  37. data/lib/samagotchi/web/reload_check_route.rb +6 -3
  38. data/lib/samagotchi/web/session_show.rb +23 -28
  39. metadata +4 -1
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: d3a8c4d1d4d37965fda091bc5c48281cdf352d6f3e496d5e5073f72777fe5994
4
- data.tar.gz: 74a26cfde1a9028c44763b99cdc60ce044028598ddd2955b244338076ef8fd86
3
+ metadata.gz: 3d57e659db748e1c159bf12ee6bea47b2d0f15b23385ceeb52f7e97b74e15f10
4
+ data.tar.gz: 68c4953fa92ad429a13b88ca27c88cd11cb4824199fbcbd5a41000e962618617
5
5
  SHA512:
6
- metadata.gz: 1de962941edd2efc63a07e566954a8e6cd212891c4858db791667341e0eca601b0e920a4661198760317f5133ee26e3411d9cad570a63a87e861527ab8e21a7e
7
- data.tar.gz: 0fb530ff96ccbfe79f2dc04b4cba6d59fc1b0ee6a921cf593907d9159b60eec1bed10c3360f1777417f30333c9afd36090d2b3abf7f58b9e4e4cf1b27e558946
6
+ metadata.gz: 05d62b9520edc30b4171a2a04efb337750d28ad12ea3e596d14a010604f06a4e2762a7e29b223fcefefbe9bf27247984affa5734c83792adf140c4ff34a598ae
7
+ data.tar.gz: 458cacd81cf57afcd8efd6be0115220bba4b5fd1183f3de39b23a5b5671740a0cadc17971f66994aa92a6e9ff1c1a4abfdb221fa746c4e38d6beb2a34c6a7a44
data/CHANGELOG.md CHANGED
@@ -8,6 +8,44 @@ and commands may change between minor versions. How releases are made:
8
8
 
9
9
  ## [Unreleased]
10
10
 
11
+ ## [0.163.0] - 2026-11-10
12
+
13
+ ### Added
14
+
15
+ - `chi project init` and `chi project` name memories saved from a project's subfolders before init (found from this
16
+ machine's sessions), and `chi project init --merge-subfolders` moves them into the project's memories folder.
17
+
18
+ ### Changed
19
+
20
+ - One way to draw a finished turn on reload. A tab opened before 0.157 shows turns without their steps until it
21
+ reloads.
22
+
23
+ Update with `chi update`, then restart chi web (it draws every finished turn from its drawing now); workers from
24
+ 0.162.0 keep working (N-1).
25
+
26
+ ## [0.162.0] - 2026-11-10
27
+
28
+ ### Changed
29
+
30
+ - chi web draws every finished turn the way it was drawn live; turns from before drawings (and past the newest 100)
31
+ are drawn from a drawing rebuilt from their messages, with small differences (no hook notices or durations that were
32
+ never kept).
33
+ - chi --attach draws the last turn the same way for every session.
34
+ - A forked session and a one-shot run keep their turns' drawings.
35
+
36
+ ### Fixed
37
+
38
+ - The copied-folder notice (two folders sharing a chi project id) no longer tells the original to take a new id: it
39
+ names both folders and says to run `chi project init --new-id` in the copy.
40
+ - chi --attach draws the last turn as live even when a note came after it.
41
+ - chi web no longer leaves a language's diagrams as source for the whole session when a renderer file's download
42
+ stalls (behind a proxy or a tunnel): the download is bounded at 15 s like the rest of the load.
43
+ - A chi-ui walk's case that goes back to its own step (a retry) is drawn disabled as "this step" instead of a button
44
+ that did nothing.
45
+
46
+ Update with `chi update`, then restart chi web and running sessions (`chi sessions restart`): workers from 0.161.0
47
+ keep working (N-1); the turn drawing changes apply to workers started by 0.162.0.
48
+
11
49
  ## [0.161.0] - 2026-11-10
12
50
 
13
51
  ### Added
@@ -6006,7 +6044,9 @@ and long-lived sessions.
6006
6044
  - A macOS desktop helper (`chi desktop install`): a "Send to chi" Service and a
6007
6045
  hotkey panel that send selected text or the clipboard to your sessions.
6008
6046
 
6009
- [Unreleased]: https://github.com/dm1try/samagotchi/compare/v0.161.0...HEAD
6047
+ [Unreleased]: https://github.com/dm1try/samagotchi/compare/v0.163.0...HEAD
6048
+ [0.163.0]: https://github.com/dm1try/samagotchi/compare/v0.162.0...v0.163.0
6049
+ [0.162.0]: https://github.com/dm1try/samagotchi/compare/v0.161.0...v0.162.0
6010
6050
  [0.161.0]: https://github.com/dm1try/samagotchi/compare/v0.160.0...v0.161.0
6011
6051
  [0.160.0]: https://github.com/dm1try/samagotchi/compare/v0.159.0...v0.160.0
6012
6052
  [0.159.0]: https://github.com/dm1try/samagotchi/compare/v0.158.0...v0.159.0
data/docs/architecture.md CHANGED
@@ -194,7 +194,7 @@ log's last 4 MB). Rows: [configuration.md](configuration.md#checking-it-chi-home
194
194
  ## Session retention & ordering
195
195
 
196
196
  - **Files:** `~/.local/state/samagotchi/sessions/<uuid>.json` + `<uuid>/input|output|owner.lock|bridge.json` (XDG-aware), and the `<uuid>/stopped`, `<uuid>/starting` and `<uuid>/archived` marker files. Durable schedules belong to the machine, not a session: `~/.local/state/samagotchi/schedules.json` and its `schedules.lock`, next to `sessions/` ([Scheduling](scheduling.md)).
197
- - **Single owner:** the process running a session's Engine (its worker, or a `--non-interactive` one-shot) holds a flock on `owner.lock` (`OwnerLock`); a second owner backs off, and the web answers 409 for a session a one-shot owns.
197
+ - **Single owner:** the process running a session's Engine (its worker, or a `--non-interactive` one-shot) holds a flock on `owner.lock` (`OwnerLock`); a second owner backs off, and the web answers 409 for a session a one-shot owns. That owner is also the one writer of the session's `turn_drawings.jsonl` (a worker's Bridge, a one-shot's own accumulator); a fork's copy of its parent's lines is written before the child's worker spawns.
198
198
  - **Status:** `status` is turn state (`idle`/`running`); liveness is the lock. A stop is the `<uuid>/stopped` marker (`Session.mark_stopped`; a resume removes it), which `Session.load` and `.summary_from_file` read as status `stopped`, so no other process rewrites a worker's session file. A resume writes nothing else: the worker, holding the lock, turns a status from before it idle (`Worker#settle_stale_status`: `stopped` with no marker, `error`, a `running` no turn is behind; not a new session's `running` whose first prompt waits), and saves at start whatever the status, which stamps `updated_at` as the resume's save did (a session woken with no turn stays young for the sweep). N-1: a newer spawner starting an older worker (a checkout's chi spawning the installed one) loses that reset; a restart covers it.
199
199
  - **Starting:** every spawn marks the session starting (`<uuid>/starting`, `{pid, at}`, `StartingMarker`) until its worker holds the lock: `spawn_worker_for_session` writes it with its own pid before `Process.spawn` and the starter's after (the starter lives until the worker holds the lock, at most `WORKER_START_GRACE`; a spawn that raises or whose starter is gone leaves none), `spawn_session` before the new file is saved, and `Worker#start` removes it. It holds for 60 s at most, and only while the pid it names runs. A resume claims it (`StartingMarker.claim`, a link(2): of resumes racing from any processes one wins), then reads the owner again. A stop marker cancels the hold-off (`start_pending?` = starting and not stop-marked) for a start marked before the stop only: of two sends after a stop, the claim lets one spawn. The stop marker carries its own `at` (`{"at"}`, on the starting marker's clock; `Session.stopped_at`), an older chi's empty one its mtime. The sweep, archive (`:starting`) and delete (refused as an owned session) honour it. N-1: an older spawner writes none for a resume (the owner checks stay); an older worker never leaves one it was given (every worker clears it at start); a leftover one is stale by age or pid (a claim's temp files a kill left, `starting.*`, count as skeleton); a 0.160 spawner or chi web still holds off on a fresh marker under a stop (it reads `starting?` before the stop), until the start ends or 60 s. `SessionManager` keeps only its starters' pids, for chi web's restart to adopt (`live_spawn_pids`), and decides nothing from them.
200
200
  - **Deleting:** `delete_session`, the retention sweep and a failed continue's cleanup use `remove_files` for the session JSON, sidecar dir, plugin state, attached context, participant grants, System 1 runs and context-candidate records. The JSON and dir go through `remove_session_files`, holding the owner lock (kind `deleting`, which `stop_session` never signals; not waited for: a worker that took it since the check keeps the session) and reading the starting marker again under it (a resume that claimed the start just before keeps the session; one after it sees the lock held). N-1: an older chi's stop reading the owner then would TERM the deleter (chi web, the CLI) in that moment; an older reader shows the kind as unknown. `Session#save` of a session read from its file (or saved once) skips a file that is gone (log `save_skipped_deleted`) rather than recreate it; only a new session's first save creates one.
@@ -641,7 +641,7 @@ A map of the parts the overview above doesn't name (paths under `lib/samagotchi/
641
641
  | LLM context strategies | `llm_context_strategy.rb`, `llm_context_view.rb`, `llm_context_stale.rb`, `llm_context_forget.rb` | What a request sends of the history (none, stale, forget) ([internals/llm-context-forget.md](internals/llm-context-forget.md)). |
642
642
  | Session chains | `session_continue.rb` (`SessionContinue`), `session_chain.rb` (`SessionChain`) | A session that continues an earlier one. `SessionChain.opener_for` gives the text web `continue →` prefills in the new link: the previous link's own first typed message when that link continues one itself, else nil (the 201's `opener`; not saved) ([sessions.md](sessions.md)). |
643
643
  | Review sessions | `review_start.rb` (`ReviewStart`), `session_review.rb` (`SessionReview`, the session's `review` field), `review_command.rb` (`ReviewCommand`, `chi review`), `review_apply.rb` (`ReviewApply`) | A session made to be shared: idle, its subjects project files checked by `Guardrails::ReviewPaths`, a fork of a working session from its recap (`--from`); Apply quotes a participant's review turn into the owner's composer ([sessions.md](sessions.md#review-sessions), [internals/participants.md](internals/participants.md)). |
644
- | chi web's routes | `web/app.rb` (`Web::App`: the gate, `ROUTES`, the shared helpers), `web/message_display.rb` (`Web::MessageDisplay`: saved messages and cards as display items, `POST /api/render`), `web/session_show.rb` (`Web::SessionShow`: `GET /api/sessions/:id` with its `cards`, `tail` and `timing` re-reads, `GET …/output`, the timing payload), `web/session_create.rb` (`Web::SessionCreate`: `POST /api/sessions`, a continue, a review fork), `web/session_control.rb` (`Web::SessionControl`: answer, command, turn and images, cancel, stop, restart, archive, delete), `web/push_routes.rb` (`Web::PushRoutes`: `/api/push`, its subscriptions, prefs, test and presence), `web/block_renderer_routes.rb` (`Web::BlockRendererRoutes`: `GET /api/block_renderers` and one renderer's file, [internals/block-renderers.md](internals/block-renderers.md)), `web/reload_check_route.rb` (`Web::ReloadCheckRoute`: `POST /api/sessions/:id/reload_check`, the opt-in `web.reload_check`'s counts from the page's `reload_check.js`, 204 and one `reload_checked` log line, with `reload_mismatch`, its `kinds`, `excused` (ACCEPTED ids) and `explained` when the turn read otherwise after a reload; the worker's version is chi web's own view, its sidecar) | The handlers `App`'s `ROUTES` name, in the file that holds their kind; each mixin is included in `App` and reads its helpers and ivars, so `app.send(:handle_show, …)` and the specs that stub `App` methods work as before. |
644
+ | chi web's routes | `web/app.rb` (`Web::App`: the gate, `ROUTES`, the shared helpers), `web/message_display.rb` (`Web::MessageDisplay`: saved messages and cards as display items, the owner show's stamped with their turns' drawings and carrying no parts (a step's ✂ marks only), the participant review's with their parts, `POST /api/render`), `web/session_show.rb` (`Web::SessionShow`: `GET /api/sessions/:id` with its `cards`, `tail` and `timing` re-reads, `GET …/output`, the timing payload), `web/session_create.rb` (`Web::SessionCreate`: `POST /api/sessions`, a continue, a review fork), `web/session_control.rb` (`Web::SessionControl`: answer, command, turn and images, cancel, stop, restart, archive, delete), `web/push_routes.rb` (`Web::PushRoutes`: `/api/push`, its subscriptions, prefs, test and presence), `web/block_renderer_routes.rb` (`Web::BlockRendererRoutes`: `GET /api/block_renderers` and one renderer's file, [internals/block-renderers.md](internals/block-renderers.md)), `web/reload_check_route.rb` (`Web::ReloadCheckRoute`: `POST /api/sessions/:id/reload_check`, the opt-in `web.reload_check`'s counts from the page's `reload_check.js`, 204 and one `reload_checked` log line, with `reload_mismatch`, its `kinds`, `excused` (ACCEPTED ids) and `explained` when the turn read otherwise after a reload; the worker's version is chi web's own view, its sidecar) | The handlers `App`'s `ROUTES` name, in the file that holds their kind; each mixin is included in `App` and reads its helpers and ivars, so `app.send(:handle_show, …)` and the specs that stub `App` methods work as before. |
645
645
  | Web Push | `web/push.rb` (`Web::Push`: `Runtime`, `preflight!`, the `web.push.*` settings), `web/push/crypto.rb` (`Push::Crypto`: RFC 8291 aes128gcm, RFC 8292 VAPID), `web/push/store.rb` (`Push::Store`, `Store::Sub`: `web-push/vapid.pem`, `subscriptions.json`), `web/push/client.rb` (`Push::Client`, `Client::Result`), `web/push/attention.rb` (`Push::Attention`: notify.js's rules in Ruby, shared cases in `spec/fixtures/attention_cases.json`), `web/push/presence.rb` (`Push::Presence`: the pages' "in front" reports), `web/push/notifier.rb` (`Push::Notifier`, a hub subscriber with a sender thread), `web/push_routes.rb` (`Web::PushRoutes`), `private_files.rb` (`PrivateFiles`, shared with the grants), `public/sw.js`, `public/push.js`, `public/manifest.webmanifest` | chi web pushes what the tab notifies for (approvals, questions, step-limit questions, cards, failed turns; done turns to a device that asks) to the owner's Home Screen app over an https public URL: the Notifier turns the hub's new attentions into show pushes after a hold, unless a chi web page is in front, at most 30 an hour, with one retry and a restart catch-up (`sent.json`) (each carries the keys still open, and the badge; no close push: every push shows a notification); the bell (`notifications.js`) subscribes the device, and the service worker and the page close the answered ones. See [internals/web-push.md](internals/web-push.md). |
646
646
  | chi web's updates | `web/update_check.rb` (`Web::UpdateCheck`), `web/update_ops.rb` (`Web::UpdateOps`), `web/auto_update.rb` (`Web::AutoUpdate`) | The RubyGems checker and its `update_check.json`; the install, worker-restart and chi-web-restart operations (one at a time) the owner's routes and AutoUpdate share; `update.auto: install`'s thread (install when no turn runs, then idle workers and chi web). See [configuration](configuration.md#unattended-updates-updateauto). |
647
647
  | Behind an auth proxy | `web/public_url.rb` (`Web::PublicUrl`: `web.public_url`, `web.proxy.identity_header`, `web.proxy.owner`), `web/proxy_gate.rb` (`Web::ProxyGate`, mixed into App; `RawHeaderNames`, prepended to WEBrick's request by `Web::Server`), `web/link_codes.rb` (`Web::LinkCodes`: the links' one-time codes), `proxy_trace.rb` (`ProxyTrace`), `web/public/token_fragment.js`, `web/public/auth_lost.js`, `web/tunnel.rb` + `web/tunnel/tailscale.rb` (`Web::Tunnel`, `Web::Tunnel::Tailscale`: `chi web --tunnel tailscale`, Tailscale Serve set for one run and the PublicUrl it makes) | Experimental: chi web behind an auth proxy. Every request needs the token; a proxied one's owner also needs the identity header (one clean value under one name); the `__Host-` cookie, an absolute `Location` from the public URL, https links with a one-time code in the fragment; the page's lost-sign-in banner. Bridges refuse proxy traces ([configuration.md](configuration.md#behind-an-auth-proxy)). |
data/docs/cli.md CHANGED
@@ -36,7 +36,7 @@
36
36
  - `chi self` — print version, source dir (checkout or installed gem), config/memory/session paths, model/host and bundles. Run by a session's `execute`, the `model` row (and host, loop, profile, thinking, served model) is **that session's** model, labelled `(this session <id8>; default …)`; elsewhere it is the default, `(default)`. `model key` is the memory overlay key (`<name>.<key>.md`), and `big memories` the memories over `memory.entry_warn_tokens` ([Memory](memory.md#a-memorys-size)), and `model notes` the model notes a prompt of that model loads (`model_notes_deepseek (system, 612 chars)`, `none`; inside a session its `--mute` list is left out). `chi self --model` prints only the model a new session starts on, an alias resolved to its target (the desktop helper's hint)
37
37
  - `chi update [--dry-run] [--to VERSION] [--json] [--no-gem] [--no-bundles] [--no-desktop]` — update an installed chi: the gem, the system bundle, the shipped bundles you installed and the desktop helper, and check the bundles from elsewhere, in one table (see [Updating](#updating))
38
38
  - `chi home`, `chi home set [--ruby PATH]`, `chi home doctor` — the chi home: the one Ruby (and its gem path) every chi launch boots, whoever launches it. `chi home` shows it (its Ruby, the newest chi in it, gem home and path, `mise`, when and by which chi it was set, and the chi you ran when that is another one; exit 1 with the problem when it can't boot chi), `set` records this chi's Ruby and gem path (or `--ruby PATH`'s own; it must have samagotchi), `doctor` checks it and what should follow it, one row each with `ok`, `warn` or `fail` and what to run (exit 1 on a `fail`; see [Checking it](configuration.md#checking-it-chi-home-doctor)). At a terminal, a chi on another Ruby than the home's says so in one dim line a day. This machine only (see [The chi home](configuration.md#the-chi-home))
39
- - `chi project`, `chi project init [--new-id] [DIR]` — this folder's project, and making a folder in no git repository one. `chi project` prints how its project was found (`kind` `git`, `marker` or `none`), its `root`, its `top` (where the AGENTS.md chain starts), a marked project's `id` (what its memories and project context are keyed on; else the root's path is) and its project `memories` folder, with a `note` for a marker a repository makes ignored, or a `$HOME` that is a git repository. `init` writes `DIR/.chi/project.yml` with a new `id:` (DIR defaults to this folder and is created when missing), so DIR and every subfolder share one memories folder (kept when DIR moves or is renamed), group their sessions and take `chi context --project`; it writes nothing in a git repository (the repository already is the project, exit 0), says so (with the id) for a folder already marked, refuses `$HOME`, a folder above it and `/` (exit 1), and marks a folder inside another marked project as its own, nested one. On a folder marked without an id (an older chi's marker) it adopts one: the folders keyed by its path move to the id, each leaving a link by its old name, and it says what moved and names memories an earlier path left (refused, exit 1, while a session of the project runs). `--new-id` gives a marked folder a fresh id with a copy of its memories and project context (a copied folder going its own way; refused elsewhere, exit 1). It prints the root, the id and the memories folder (with the memories already there: a folder chi ran in at its top keeps them, moved to the id), the running sessions in DIR to restart (`chi sessions restart ID`: their prompt keeps the old project) and, when DIR has saved sessions, that a running chi web groups them after its restart. This machine only. See [Projects without git](memory.md#projects-without-git)
39
+ - `chi project`, `chi project init [--new-id | --merge-subfolders] [DIR]` — this folder's project, and making a folder in no git repository one. `chi project` prints how its project was found (`kind` `git`, `marker` or `none`), its `root`, its `top` (where the AGENTS.md chain starts), a marked project's `id` (what its memories and project context are keyed on; else the root's path is) and its project `memories` folder, with a `note` for a marker a repository makes ignored, or a `$HOME` that is a git repository. `init` writes `DIR/.chi/project.yml` with a new `id:` (DIR defaults to this folder and is created when missing), so DIR and every subfolder share one memories folder (kept when DIR moves or is renamed), group their sessions and take `chi context --project`; it writes nothing in a git repository (the repository already is the project, exit 0), says so (with the id) for a folder already marked, refuses `$HOME`, a folder above it and `/` (exit 1), and marks a folder inside another marked project as its own, nested one. On a folder marked without an id (an older chi's marker) it adopts one: the folders keyed by its path move to the id, each leaving a link by its old name, and it says what moved and names memories an earlier path left (refused, exit 1, while a session of the project runs). `--new-id` gives a marked folder a fresh id with a copy of its memories and project context (a copied folder going its own way; refused elsewhere, exit 1). Memories a session on this machine saved in a subfolder before init (keyed by that subfolder's path) are named by `init` and by `chi project` (a `note`); `--merge-subfolders` moves them into the project's memories folder (marking DIR first when it isn't yet): a memory the project has by that name, or a bundle's, stays and is named, an emptied folder is removed; refused, exit 1, while a session in DIR runs; not with `--new-id` (exit 2). It prints the root, the id and the memories folder (with the memories already there: a folder chi ran in at its top keeps them, moved to the id), the running sessions in DIR to restart (`chi sessions restart ID`: their prompt keeps the old project) and, when DIR has saved sessions, that a running chi web groups them after its restart. This machine only. See [Projects without git](memory.md#projects-without-git)
40
40
  - `chi bundle install|upgrade|uninstall|status|diff|list|build|trash|new|test|check` — manage memory bundles (see [Plugins](plugins.md) and [Bundle hooks](hooks.md#bundle-hooks)); `list` shows the installed ones and the ones shipped with chi, which `install <name>` installs; `upgrade <name>` upgrades an installed bundle by name from the source it came from (its folder, archive or git URL), `upgrade <source>` from a new one; `core` and `dev` are profiles that install a set of them (see [Bundle profiles](memory.md#bundle-profiles-core-and-dev), [Guardrails](guardrails.md), [Bundles](bundles.md#the-btw-bundle), [the mcp bundle](bundles.md#the-mcp-bundle) [the loop-guard bundle](bundles.md#the-loop-guard-bundle), [the check-in bundle](bundles.md#the-check-in-bundle) and [the skills bundle](bundles.md#the-skills-bundle)). `trash` lists and empties the bundle trash (moved files from uninstalls/upgrades). `install`/`upgrade` `--force` overwrites existing entries and also installs a bundle whose `requires_chi` this chi doesn't meet and a memory, plugin or script whose bytes disagree with its manifest `sha256`; without it such a bundle or file is refused (exit 1), nothing written. A plain `install` of a bundle that is already installed from the same source rewrites its rules, plugin, scripts and record: the summary lists a file that already holds the bundle's bytes as `Up to date: …`, one you wrote as `Skipped: …`, and ends with `NAME was already installed from SOURCE: its rules, plugin and scripts now match it and its record was rewritten` (plus, when a memory was kept, `your own copies of its memories were kept (chi bundle upgrade NAME merges the bundle's changes into them)`). A source with class-file hooks (`hooks/*.rb` or a manifest `hooks:` entry) is refused, `--dry-run` too; an older install's hooks are removed by the next install or upgrade (`Removed (chi no longer loads class-file bundle hooks): …`, an edited one copied to the trash first; see [Class-file hooks are retired](hooks.md#class-file-hooks-are-retired)). `status NAME` lists the bundle's guardrail rules and scripts beside its plugin, each `[ok]`, `[missing]` or `[modified]` (edited: the next install replaces it, its copy kept in the trash; an edited rule doesn't load, so it counts in `issues=`), and `diff NAME` names an edited rule or script with its recorded and current sha256 (chi keeps no base text for them). A usage error (an unknown subcommand or flag, a missing argument, a bad `build --scope`) exits 2, as for the other subcommands. Plain `chi` and `chi web` exit 1 on an unknown flag, a flag missing its value or a stray argument. `new`, `test` and `check` are for writing one: see [Writing a bundle](#writing-a-bundle-new-test-check)
41
41
 
42
42
  - `chi guardrails replay [--dry-run] [--threshold T] [--model M]` — seed System 1's record from the approvals this machine's sessions already answered: each ask is judged by the configured model and written to `guardrails/judgments.jsonl` with the answer the user gave, then a per-rule table prints (asks, allowed, denied, would-be auto-allows, false allows, asks with no judgment). A parent agent's answer is not the user's: only its deny is replayed, and only where the parent could have allowed. `--dry-run` judges without writing, `--threshold` overrides `guardrails.system_one.threshold` for the table, `--model` the configured model for this run. Exit 2 when `guardrails.system_one.mode` is off or no `host` is set; a usage error exits 2 (see [System 1](guardrails.md#system-1-experimental))
@@ -2378,7 +2378,7 @@ column says so, a `--kebab-name` flag. The maps (`hosts:`, `models:`,
2378
2378
  | `web.host` | `127.0.0.1` | yes | `127.0.0.1`, `::1` or `localhost`; `lan` (this machine's private IPv4 address) or one of its IPv4 addresses also opens `chi web` to the network, with an access token, asked of this machine's 127.0.0.1 too (its `Local:` link carries a one-time code; `chi web --new-token` replaces the token). Anything else binds `127.0.0.1` with a warning. See [CLI: chi web on your phone](cli.md#chi-web-on-your-phone). |
2379
2379
  | `web.markdown` | `false` | yes | Render answers as Markdown in `chi web`. |
2380
2380
  | `web.working_set` | `true` | yes | The stage view's working set: the files, memories and URLs a turn brought into the model's context, in a rail in the stage, a footprint as each finished turn's block summary and a `set N` chip in place of the mem chip; `false` brings the mem chip back. `?working_set=1` or `?working_set=0` on the page URL overrides it for that page load. See [CLI: the working set](cli.md#the-working-set). |
2381
- | `web.reload_check` | `false` | yes | Opt-in: once each finished turn has moved into the history, the page reads the session again (one full read per turn end), draws that turn as a reload would and compares the two, strictly: a known divergence counts as a mismatch too. `chi web` logs one `reload_checked` line per check and a `reload_mismatch` line naming the kinds that differed, `excused` (the known divergences, `history_shape.js` `ACCEPTED`, that would explain them) and `explained` (all of them had one), with `turn_id`, `drawn` (the turn came back from its drawing, so a mismatch with `drawn: true` is a drawing bug) and the worker's version: counts only, never content. The count is `grep -c reload_mismatch` over `grep -c reload_checked` in chi web's log, split by `excused`. Cards are left out: a reload places them after the render, which the check doesn't run (the e2e reload checks compare them). Every open owner tab runs the check; `chi web` logs a turn's first report only, and starts over when it restarts. |
2381
+ | `web.reload_check` | `false` | yes | Opt-in: once each finished turn has moved into the history, the page reads the session again (one full read per turn end), draws that turn as a reload would and compares the two, strictly: a known divergence counts as a mismatch too. `chi web` logs one `reload_checked` line per check and a `reload_mismatch` line naming the kinds that differed, `excused` (the known divergences, `history_shape.js` `ACCEPTED`, that would explain them) and `explained` (all of them had one), with `turn_id`, `drawn` (the turn came back from its drawing, so a mismatch with `drawn: true` is a drawing bug), `undrawn` (how many of the reload's rows came without their turn's drawing, the page's plain fallback: 0 unless chi web missed a turn) and the worker's version: counts only, never content. The count is `grep -c reload_mismatch` over `grep -c reload_checked` in chi web's log, split by `excused`. Cards are left out: a reload places them after the render, which the check doesn't run (the e2e reload checks compare them). Every open owner tab runs the check; `chi web` logs a turn's first report only, and starts over when it restarts. |
2382
2382
  | `web.annotate_presets` | `Agreed\|Could you please elaborate?` | yes | Quick replies next to Annotate in `chi web`, `\|`-separated (a YAML list works too); `""` in the file or on the CLI leaves only Annotate (an empty env value means the default). See [CLI](cli.md#web-annotate-presets). |
2383
2383
  | `web.editor` | `vscode` | yes | What a file ref in `chi web` (a file tool row's title, a diff line) opens, for a viewer on this machine: a preset (`vscode`, `vscode-insiders`, `cursor`, `zed`) or a URL template with `{path}` and an optional `{line}`; `none` turns refs off. See [Opening files from chi web](#opening-files-from-chi-web). |
2384
2384
  | `web.start_dir` | the folder `chi web` runs in | | The folder `chi web` starts in (`chi web --start-dir DIR` for one run): its page (the printed link, a bare `/`, the LAN link and QR code, the Home Screen app) opens on that folder's project, outside a project (no repository or marked folder) on every session, and a new session from the all view starts there; the header's project picker switches projects. `~` and a relative path (resolved from your home folder) work; one that isn't a folder stops `chi web` from starting. `chi web` never changes its own folder. See [CLI](cli.md). |
@@ -30,7 +30,8 @@ model. The TUI is untouched: it shows a fence as source.
30
30
  move isn't over when it is seen:** a block waiting to come near is watched by its scroller's observer, so one that moves
31
31
  to another scroller (the stage's `.ts-scroll` hands a long answer to `#history`) is watched there, or it never draws.
32
32
  4. `block_frame.js` (`createBlockFrame`): one hidden frame per language, made on first need, one render at a time, 15 s per
33
- call. A timeout, a dead frame or a session switch drops it. Handshake `loaded` → `code {files}` → `ready | failed`,
33
+ call, the renderer files' fetch included (browser `fetch` has no timeout; a fetch past it is a failed load). A timeout, a
34
+ dead frame or a session switch drops it, and a drop rejects whatever is pending, the load too. Handshake `loaded` → `code {files}` → `ready | failed`,
34
35
  then `render {id, source, theme}` → `done {id, svg} | error {id, message}`.
35
36
  5. On success a `<figure class="block-drawn">` goes right before the `<pre>`, which stays in the DOM, `hidden`, so whatever
36
37
  reads text (copy, a claim's walk, fold thresholds) sees what it did. **The DOM is the state** (`block_source.js`): a Revise
@@ -77,7 +78,7 @@ is model-written**, so a renderer bug or an injected diagram must not reach a pa
77
78
  has origin `null` and can't read chi's API; WebKit may still attach a same-host cookie to a request it makes (seen with a
78
79
  test cookie to another port), so what holds is that the answer stays unreadable, not that no cookie is ever sent.
79
80
  3. The page accepts messages only where `e.source === frame.contentWindow`, of known types, and treats them as data
80
- (`frameMessage`). No other window `message` listener exists on the page.
81
+ (`frameMessage`). No other window `message` listener exists on the page (`spec/web/public/message_listeners.test.js` keeps it so).
81
82
  4. Code enters the frame by postMessage from the page's own authenticated fetch (the frame's CSP closes its network but for
82
83
  WebRTC, the residual risk below, and it has no cookie),
83
84
  then as `script.text = code`. `eval` doesn't work: a library's `"use strict"` keeps its global local. A syntax error doesn't
@@ -59,14 +59,16 @@ a participant's review turn runs, so the owner's input queues behind it.
59
59
 
60
60
  ## TurnDrawings
61
61
 
62
- A reload or a reconnect draws a finished turn from what live drew, not rebuilt from its saved messages: the
63
- accumulator's final fold of the turn (its parts in order, in-turn cards included) and the end event's display keys
64
- (`TurnDrawings::END_KEYS`), one JSON line per turn in `<session dir>/turn_drawings.jsonl`
65
- (`{v: 1, turn_id, kind, from, to, from_digest, to_digest, drawing, end}`, `TurnDrawings::Line`).
62
+ A reload or a reconnect draws every finished turn from a drawing, never rebuilt into rows from its saved messages:
63
+ the accumulator's final fold of the turn (its parts in order, in-turn cards included) and the end event's display
64
+ keys (`TurnDrawings::END_KEYS`), one JSON line per turn in `<session dir>/turn_drawings.jsonl`
65
+ (`{v: 1, turn_id, kind, from, to, from_digest, to_digest, drawing, end}`, `TurnDrawings::Line`). A turn live wrote
66
+ no line for (an older worker's, one from before drawings, a dropped one) gets one made from its messages at read
67
+ (`TurnDrawings::Synth`, below), so the page and the TUI have one way to draw a turn.
66
68
 
67
69
  - **The range comes from the Engine.** The end event's `kept_from`/`kept_to` (`Engine#end_turn`) name the turn's own
68
- messages, `kept[from...to]`. No range (an older worker, a turn that kept nothing) or an empty one writes no line,
69
- and the turn draws as before.
70
+ messages, `kept[from...to]`. No range (an older worker, a turn that kept nothing) or an empty one writes no line:
71
+ the turn is made from its messages at read.
70
72
  - **Validity.** A line holds while the messages reach `to` and `messages[from]` and `messages[to - 1]` digest as the
71
73
  line says (`TurnDrawings.digest`: role, content and time, one canonical form for the live symbol-keyed messages
72
74
  and the saved, scrubbed ones). A rollback, a rolled-back failure or a prompt handed back drops it. Of overlapping
@@ -77,28 +79,89 @@ accumulator's final fold of the turn (its parts in order, in-turn cards included
77
79
  "enqueue-only" note, as CardStore's save does: one append per turn end. It writes `"\n"` first when the file's last
78
80
  byte isn't one (a torn line from a crash), then the line in one write; a failure is logged (`turn_drawing_failed`).
79
81
  A part's output is the accumulator's cut (`WEB_PREVIEW_CHARS`); a diff is the one the saved `tool_diffs` have
80
- (`TextDiff`'s cut); images are refs.
82
+ (`TextDiff`'s cut); images are refs. The writer is the session's owner under `OwnerLock`: its worker's Bridge, or a
83
+ `-p X --non-interactive` one-shot, whose `TerminalUI#run_one_shot_turn` tees its events to an accumulator with the
84
+ same hook. A fork's child starts with its parent's lines that hold against its seed (`TurnDrawings.carry`, in
85
+ `Plugin::Sessions#fork`'s `before_spawn`, before the child's worker exists: same indices, same digests; a range
86
+ whose end the image copy changed is dropped and made from its messages at read). A seed without the system head (a
87
+ plugin's `ctx.messages`) is checked as the child's messages will be once its first turn puts the head back: the
88
+ lines keep the parent's indices, so until that turn they don't hold and their turns are made from the messages.
81
89
  - **Reading.** `TurnDrawings.read(dir)` skips an unknown `v`, a torn or broken line and one missing a field, and is
82
90
  cached by the file's path, size and mtime. `#last` is the newest line this worker wrote or started from.
91
+ `TurnDrawings.cover(lines, messages, timing:, entries:, skip_turn_id:, session_id:, cwd:)` is what a show draws
92
+ finished turns from (pure): `valid`'s lines, and for each `TurnRanges` range none overlaps (the running turn's
93
+ left out), a line `Synth.memoized` makes from its messages, the timing's records and CardStore's entries. A range a
94
+ kept line overlaps only in part (a Continue's steps, which `TurnRanges` reads as the turn before's, with only one
95
+ of the two lined: drawings that start partway through a session) is split at the lines' bounds and the rest made:
96
+ a part with the turn's opening keeps its id and record, one without is `<id>~<from>` (no record, no entries), so no
97
+ turn item is left without a line. A made range whose id a kept line has (a failed turn's kept steps, then its
98
+ re-run under that id) is renamed `<id>~<from>`, so no two lines share an id; it gets no record, so no timing line
99
+ (the two runs' records share the id: `Synth::LOSSES` `repeated_turn_id`). `TurnRanges.of(messages)` (`bridge/turn_ranges.rb`) reads a session's turns
100
+ back from its messages as the Engine cuts them (`kept_from…kept_to`: the reminders before an opening start a turn; a
101
+ note after it, a `!cmd`'s record and a wake's note stay outside), with a display id for a turn with none
102
+ (`m<from>-<digest8>`) or a repeated one (`<id>~<from>`); `TurnRanges.records` pairs each with its turn record by id,
103
+ else by place among the openings, as `timing.js turnGroups` does (`spec/shared/turn_ranges.json` holds the cases both
104
+ suites read).
105
+ - **Made from the messages.** `TurnDrawings::Synth` (`bridge/turn_drawings/synth.rb`; chi web's show, `cover`) makes
106
+ a turn's line from its saved messages, for a `TurnRanges` range no live line covers: the events live would have
107
+ emitted (`turn_started`, the reminders, each step's thinking, text and calls with `MessageParts`' fields and the
108
+ output as `preview:`, steers and merged lines, the end from the turn record), folded by a fresh `TurnAccumulator`,
109
+ so every drawing comes from the one fold. The turn's tool records give each row's status and duration (by tool, in
110
+ call order), and CardStore's entries of the turn (`of_turn`) go in at the step they name (`iteration`, `calls`; an
111
+ in-turn card keeps them too): its cards, hook notices, retries (a retried step is drawn empty), steer cuts, ✂ rows
112
+ and questions. A made-up id (`m…`, `…~<from>`) stays off the end's `turn_id` (no Revise); the end carries the
113
+ record's `record_id`. `Synth::LOSSES` lists what it can't have (a prompt's origin, a merged line's senders, a
114
+ retried step's thinking, evicted CardStore entries, untimed rows, …; `events_drift_spec` makes each `:row` event
115
+ synthesized or listed; a repeated id's later range and a Continue's steps read as its turn's are declared too).
116
+ The fold raises what it can't fold (`TurnAccumulator.new(raise_errors: true)`), and `safe_line` never raises: a
117
+ minimal line (opening, end kind, no parts, `turn_synth_failed`, once), else a constant one (`constant`: the range and
118
+ a completed end); `memoized` keeps lines per range (key: session, range, every message's digest in it, the turn's
119
+ records and its entries without CardStore's listing fields) in a process-wide LRU of `MEMO_BYTES`.
83
120
  - **The snapshot.** `Bridge#snapshot` (the snapshot and reset frames, `GET /snapshot`) adds `last_turn_drawing:
84
- {drawing, end}`, `#last` as the file has it, not unfolded, when it holds against the snapshot's messages and its `to`
85
- is their size (the last exchange); it is absent otherwise (no turn yet, a rollback, a Continue's note after it, a line
86
- of another version, one over the 1 MB a restart reads back: `TurnDrawings.sendable?`). An attaching TUI unfolds it (`TerminalUI::JoinReplay`, `TurnAccumulator.replay_events`) and draws
121
+ {drawing, end}`: the line of the last prompt's turn (the last user message that opens a turn, the one the TUI draws),
122
+ the newest for that turn id that holds against the snapshot's messages (`#last`, else the file's, `TurnDrawings.read`),
123
+ not unfolded, when that turn is the last one (`TurnRanges`: a note after it doesn't hide it). It is absent otherwise:
124
+ a later turn with no prompt (a reminder's, a Continue's: a join would draw the prompt's rows, then the later turn's
125
+ answer without its rows), no prompt with a turn id, a rollback, a line of another version, one over the 1 MB a
126
+ restart reads back (`TurnDrawings.sendable?`). An attaching TUI unfolds it (`TerminalUI::JoinReplay`, `TurnAccumulator.replay_events`) and draws
87
127
  that turn's rows through its `EventRenderer`, as a running turn's join does, then the end event's cancel or failure
88
- line, else the saved answer; without it (or for a drawing that isn't the last prompt's turn: a reminder's, a
89
- Continue's) the rows are rebuilt from the messages as before. `chi --remote` attaches through chi web's stream proxy,
128
+ line, else the saved answer. Without it (an older worker, a line over 1 MB, a turn from before drawings) the TUI
129
+ makes that turn's line itself: `TurnRanges.of` over the snapshot's messages finds the prompt's range, and
130
+ `Synth.safe_line` draws it with the link's saved records (`LocalLink`, or `RemoteLink#saved_turn_record` /
131
+ `#saved_tool_records` through chi web for `--remote`) and the snapshot's cards, through the same renderer. Nothing
132
+ rebuilds rows from the messages any more. `chi --remote` attaches through chi web's stream proxy,
90
133
  which relays an owner's frames byte for byte, the field included. A participant never gets it: its stream's snapshot
91
134
  is bare (`ParticipantView`). An older TUI ignores the field; an older worker sends none.
92
- - **The show.** chi web's full read with `?parts=1&drawings=1` (the page's) stamps each display item of a kind a
93
- drawing draws (the opening, steps, steers, merged lines, the empty answer) in a valid range with `drawn: <turn_id>`
94
- and drops its `parts` (its ✂ marks stay as `marks: {tool_id => edit}`), and sends `turn_drawings: {turn_id =>
135
+ - **The show.** chi web's full read (`GET /api/sessions/:id`, whatever its query: a tab from before 0.157 still sends
136
+ `?parts=1`) draws every finished turn from a line: `SessionShow#drawn_lines` is `TurnDrawings.cover` over the file,
137
+ the show's timing records and its cards (CardStore's list, live or saved), the running turn (`current_turn`'s id)
138
+ left out. A file that can't be read gives no lines, so every turn is made from its messages; should the cover
139
+ itself fail (`turn_drawings_uncovered`), no item is stamped and the page draws each as a plain row (its fallback,
140
+ web-frontend.md). `MessageDisplay#messages_for_display(drawings:)` stamps each display item of a kind a drawing
141
+ draws (the opening, steps, steers, merged lines, the empty answer) in a line's range with `drawn: <turn_id>`; the
142
+ items carry no `parts` (a step's ✂ marks come as `marks: {tool_id => edit}`, read from its parts only for a step
143
+ whose outputs carry one; a text-less step stays as an empty item), and the show sends `turn_drawings: {turn_id =>
95
144
  {events, end}}`: `TurnAccumulator.replay_events(drawing, cards: true)`, the one unfold, in Ruby. A context note in
96
- a range and a `!cmd`'s record are not stamped. Without `drawings=1` (an older page) the read is what it was.
97
- CardStore lists an in-turn entry's turn as `of_turn`, so the page leaves a drawn turn's own rows and cards to its
98
- drawing (`cards_place.js`). A live worker whose sidecar features lack `turn_drawings` (`TurnDrawings::FEATURE`:
99
- an older one lists no `of_turn`) gets no drawings in the show: its turns all draw as before.
100
- - **Compat.** An older worker writes nothing (its turns fall back); an older chi web never opens the file. A fork
101
- or a continue copies no drawings: its turns fall back. A one-shot run (no Bridge) writes none.
145
+ a range and a `!cmd`'s record are not stamped. CardStore lists an in-turn entry's turn as `of_turn`, so the page
146
+ leaves a drawn turn's own rows and cards to its drawing (`cards_place.js`). Every supported worker (0.161.0 and
147
+ later) lists `TurnDrawings::FEATURE` in its sidecar; the show no longer asks. The stamps walk the lines with one
148
+ cursor and the unfold reads a Set of stamped ids, so a long session's show is linear in its turns; a made-up line
149
+ is memoized per range (`Synth.memoized`), so a show after a turn end makes no old turn again. What each step did
150
+ as message parts (`MessageParts`, `parts: true`) is the participant review's only (`ParticipantReview`, frozen on
151
+ its message model).
152
+ - **Compat.** An older worker writes nothing, a continue (a note, no turns) and a review fork copy no drawings, and
153
+ an older chi's fork or one-shot wrote none: their turns are made from their messages. A `/btw keep` child forked
154
+ before its first turn (saved without its system head) draws its turns made from its messages, without CardStore
155
+ rows, until that turn puts the head back and its carried lines hold (`Synth::LOSSES` `fork_before_first_turn`;
156
+ `Plugin::Sessions#fork`'s seed is left as it is). A tab opened before 0.157 asks `?parts=1`, gets no parts and
157
+ draws those turns without their steps until it reloads. The lines a fork carries and a
158
+ one-shot writes are plain `v: 1` lines, which an older chi web draws as any. An older chi web never opens the file and draws them as it
159
+ did. A made-up line's end has no `turn_id` for a made-up id and names its record (`record_id`), which a 0.157+ page
160
+ reads as any drawn turn's (an older page ignores `record_id` and finds no record for such a turn: no timing line;
161
+ it also keys such a turn's answer by the made id, `data-answer-turn`, until a reload: only a turn saved before turn
162
+ ids or a repeated id's, never a wake turn, which has its own id).
163
+ `release:bump`'s compat corpus has a session with a line (`compat-drawn`) and one without; `readers_spec` checks
164
+ every turn of both is stamped.
102
165
 
103
166
  ## CardStore
104
167
 
@@ -390,7 +453,7 @@ The Bridge exposes:
390
453
  - `GET /session/:id/activity` — `Worker#activity_snapshot`: `{session_id, turn_running, input_pending, awaiting_continue, open_streams, reminders, tasks_holding}` — what a `chi schedule tick` asks a live worker before it fires (the tick runs out of process and cannot read a worker's memory). Read-only and small (under 300 bytes). `501 activity_unavailable` when this Bridge was built without an `on_activity:` step; the worker advertises it in `Bridge::FEATURES` (`activity`). See [scheduling.md](../scheduling.md).
391
454
  - `GET /session/:id/snapshot` — the snapshot frame's content as one request (the web server renders
392
455
  the messages itself, then streams from its `event_seq`). Read by the web's full show
393
- (`GET /api/sessions/:id`, `?parts=1`) and the plugin's `list_sessions`; every message is copied.
456
+ (`GET /api/sessions/:id`) and the plugin's `list_sessions`; every message is copied.
394
457
  - `GET /session/:id/tail` — the page's light re-read (`Bridge#tail_frame`): `session_state_snapshot`,
395
458
  `working_directory` (the session's folder, which the web checks the answer's file refs against),
396
459
  `answer` (the last message a UI shows as an answer, `AnswerTail`: the one message, copied alone),
@@ -24,7 +24,10 @@ its spec holds to a strict parse. Without it nothing here changes, and blocks al
24
24
  drawers for one block.
25
25
 
26
26
  **Safety.** The JSON is an attribute value: Nokogiri escapes its quotes, and `<`, `>` and `&` in it are `\u` escapes
27
- (`JSON_MARKUP`), so the HTML holds no model markup even as attribute text. The page draws its strings as text.
27
+ (`JSON_MARKUP`), so `data-widget`'s JSON holds no model markup even as attribute text. `data-widget-error` is not
28
+ escaped that way: a refusal quotes model values (`recommended "<b>z</b>" isn't one of its options`), so it can hold a raw
29
+ `<` or `>` inside its quoted value. The page reads it only as data (`failBlock`'s dataset, CSS, `aria-label`), never as
30
+ markup, and no consumer should treat rendered HTML with a regex. The page draws all strings as text.
28
31
 
29
32
  ## The parse (`Samagotchi::InlineWidgets`)
30
33
 
@@ -52,7 +55,7 @@ Pure Ruby, no web, no Engine. `parse(source)` returns a `Result`: `ok?`, `type`,
52
55
  the key to the value's end when both sit on one line, else `key: value`. The Result is then `lenient?`. A mapping
53
56
  of several pairs, or one holding a list or a mapping, stays an error, and so does one where an id, an actor, a
54
57
  `next` or a `goto` goes. This is a mend, not a second lenient pass (`Tree#folds`, `Schema#text`).
55
- - **Normalised.** Ids are strings, unknown keys are dropped, optional values are absent rather than null, and text is
58
+ - **Normalised.** Ids are strings, unknown keys are dropped, a repeated key is last-wins (`Tree#mapping`), optional values are absent rather than null, and text is
56
59
  stripped. The page never sees model junk.
57
60
 
58
61
  ### The schemas
@@ -60,7 +63,7 @@ Pure Ruby, no web, no Engine. `parse(source)` returns a `Result`: `ok?`, `type`,
60
63
  | | Required | Optional | Rules |
61
64
  |---|---|---|---|
62
65
  | picks | `rows`: rows of `id`, `text`, `options` (2-4 texts) | `title`; on a row `recommended`, `why` | ids unique; a row's options unique; `recommended` is one of the options |
63
- | walk | `title`, `actors` (2-5 texts), `steps`: steps of `id`, `actor`, `does` or `sees` | on a step `behind`, `next`, `cases` (each `when` + `goto`) | ids unique, none of them `end`; actors unique; `actor` is one of the actors; `next` names a step or is `end`, and not the step itself; every `goto` names a step |
66
+ | walk | `title`, `actors` (2-5 texts), `steps`: steps of `id`, `actor`, `does` or `sees` | on a step `behind`, `next`, `cases` (each `when` + `goto`) | ids unique, none of them `end`; actors unique; `actor` is one of the actors; `next` names a step or is `end`, and not the step itself; every `goto` names a step, its own included (a retry, as models write it: the page draws that case disabled, "this step") |
64
67
 
65
68
  Eval round 1's `branches:` (the same shape as `cases:`) is read as `cases`.
66
69
 
@@ -52,7 +52,7 @@ change.
52
52
  | **`store.sessions`** (the hub's projection) | every card | `store.update({sessions})` from app.js: `openSessionEvents` (`applySessionEvent`), `refresh` (the list fallback), `addCreatedSession`, `applyView` (re-sorted), `replaceSelectedCard` (`setLiveStatus` through `setStatus`, `readTurnEnd`, `setUsedMemories`), the stream's close (`withoutWorker`); `session_actions.js` (`setSessions`) | the store: `lists` and `infoBar`. **Always a new array**; an entry is replaced, never changed in place. `followSelectedSession` copies the open one's owner and worker (`fieldsFromCard`) and, when not streaming, its status (`setStatus(…, "hub")`) into `store.current` |
53
53
  | **Factory closures**: the `create*` factories (popovers, panels, views) | each component's own state: open-for, busy, error, its own fetched list | the factory | an `onChange` hook back into app.js, or a getter the factory reads at draw time |
54
54
  | **The history DOM** | the conversation as drawn: which turn a bubble belongs to (`data-turn-id`, `data-answer-turn`), what opens a turn (`TURN_PROMPT`, `bubbles.js`: a prompt or a wake's note, the same turns `Steer.turn_opening?` counts for a card's `turns_since`), an opening's id for a card's and the saved recap's stamp (`data-turn-id` on a prompt, `data-opening-id` on a wake's note or `/continue no`'s reason line; `card_stamps.js` places a snapshot's card after the stamped opening, `recap_stamp.js` the saved recap after the last turn it covers, each by its count (`turns_since`) only without one), kept command bubbles, which texts were shown, unnamed badges, folded answers and long prompts (`.folded`), Revise stamps (`data-revises` on a prompt; a Verify turn's `data-verify`) and the stacks' folded versions (`.stack-hidden`, `.stack-stub.open`); the switcher's version on view is `revise_stack.js`'s own (a copy `.stack-view` before the top answer, the top `.stack-swapped`; never stored) | `bubbles.js`, `cards_place.js`, `question_cards.js`, `turn_block.js`/`stage_view.js`, `answer_fold.js`, `revise_stack.js`, `stream_handlers.js` (a live `turn_completed`'s `revises` and `verify` onto its prompt) | read back as state: `turn_range.js turnElements` (one walker for a turn's elements), `keptCommandBubbles`, `seedSeenFromDom`, `nameUnnamedBadges`/`nameVerdictCards`, `answer_fold.js` and `revise_stack.js` (their observers decorate every path that fills `#history`; the stacks are `stacks()` of the stamps, read again on each change, never a store field), `history_reveal.js revealInHistory` (the one way a jump unfolds what hides its target) |
55
- | **A drawn turn** (`turn_drawings` of the full read, `?parts=1&drawings=1`) | a finished turn as live drew it: `turnGroups` makes its stamped items (`drawn: <turn_id>`) one group, and `turnHistoryNodes` draws it by feeding its drawing's events to a live turn block offscreen (`turn_block.js drawnTurnNodes`: the block's own handlers, as the stage's), the stage's extras (a reminder, merged lines, a card that asks or warns) and end as live, then the answer, the merged lines and the steps' texts from their saved items (markdown, refs). Each of its top-level elements carries `data-drawn`: `cards_place.js` leaves that turn's in-turn CardStore entries (`of_turn`) to it, and a kept reminder bubble of that turn (`data-turn-id`) stays out after a resync. A turn without a drawing is rebuilt from its messages as before | chi web (the show) | `renderHistory`, the reload check's render |
55
+ | **A drawn turn** (`turn_drawings` of the full read) | every finished turn, as live drew it: `turnGroups` groups by the stamps only, a turn's stamped items (`drawn: <turn_id>`) one group, and `turnHistoryNodes` draws it by feeding its drawing's events to a live turn block offscreen (`turn_block.js drawnTurnNodes`: the block's own handlers, as the stage's), the stage's extras (a reminder, merged lines, a card that asks or warns) and end as live, then the answer, the merged lines and the steps' texts from their saved items (markdown, refs). Each of its top-level elements carries `data-drawn`: `cards_place.js` leaves that turn's in-turn CardStore entries (`of_turn`) to it, and a kept reminder bubble of that turn (`data-turn-id`) stays out after a resync. chi web sends a drawing for every finished turn (one made from its messages where live wrote none): `drawnGroup` pairs the record the end names (`end.record_id`, by place for a turn saved before turn ids), else by the turn's id, and the answer's `data-answer-turn` is the end's own `turn_id` only (a made-up id, `m…` or `…~N`, keys none: no Revise). Nothing is rebuilt from messages: an item that comes unstamped is a `plain` group drawn as a plain row of its text (its prompt or answer bubble, no steps), the running turn's as expected (`runningTurnId`, the show's `current_turn`: it has no line yet), any other a miss, marked `data-undrawn`, logged once per render (`console.warn`) and counted by the reload check (`undrawn`), never a throw; a drawing with no parts (a minimal line) draws its prompt, answer and end | chi web (the show) | `renderHistory`, the reload check's render |
56
56
  | **localStorage** (`storage.js` `readStored`/`writeStored`, guarded) | per-browser choices only | the module that owns the choice | read at start (see Storage keys) |
57
57
  | **SSE** | see Streams | the server | owner page: events go into the DOM directly; participant page: an event marks the data stale |
58
58
 
data/docs/memory.md CHANGED
@@ -36,7 +36,13 @@ the folder is left as is: it is created when missing, nothing is marked).
36
36
  id. A later `git init` in the folder makes it a repository, keyed by its path again (git wins): its
37
37
  memories stay in the id folder until you move them, and chi names the id folder at session start
38
38
  (and under a `memory_read` miss) while the repository's own folder holds no memories. Memories saved from a *subfolder* before
39
- `init` stay in that subfolder's own folder: move them by hand if you want them in the project's.
39
+ `init` stay in that subfolder's own folder (keyed by its path); `chi project init` and `chi project`
40
+ name the ones a session on this machine saved, and `chi project init --merge-subfolders` moves them
41
+ into the project's folder (each memory with its model overlays and index line; one the project has by
42
+ that name, or a bundle's, stays and is named; an emptied folder is removed, with no link: every chi
43
+ that knows markers resolves the subfolder to the project). It refuses while a session in the
44
+ project runs. Memories only: a subfolder's project context sources stay. Ones older than the
45
+ sessions kept (14 days / 500) aren't found: move them by hand.
40
46
  A hand-edited id must be letters, digits, `_`, `.` or `-` (up to 64, a letter or digit first);
41
47
  anything else (or a broken file) is ignored and the project keyed by its path (a debug log line
42
48
  says why, `chi project init` reports it).
@@ -47,7 +53,7 @@ the folder is left as is: it is created when missing, nothing is marked).
47
53
  the old folder mid-move), and names memories an earlier key left (the same folder name with
48
54
  another path's hash: moved before it had an id, or a `chi project init` id folder,
49
55
  `<basename>-<8 hex>`, left behind when `git init` turns that marked folder into a repository),
50
- merging nothing. A link stays behind: a new
56
+ merging nothing (memories saved from a subfolder: `--merge-subfolders`, above). A link stays behind: a new
51
57
  folder (or git repository) made later at the old path reaches the moved project's memories
52
58
  through it; delete the link to stop that. chi web's project picker marks a new folder with an id
53
59
  but never moves folders: a folder it marks that already has path-keyed memories gets no id until
data/docs/sessions.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Sessions
2
2
 
3
- Sessions are plain files — no DB. Each session is `~/.local/state/samagotchi/sessions/<uuid>.json` (XDG-aware via `XDG_STATE_HOME`) plus a sidecar dir `<uuid>/` with `input/`/`notes/`/`output/`/`owner.lock`/`bridge.json` (`Session.session_dir`), `turn_drawings.jsonl` once a turn ended with a Bridge (each finished turn as live drew it, which the web's reload draws: [bridge.md](internals/bridge.md#turndrawings)), and `tool_output/` once a long `execute` result was cut: its whole output, which the cut result names (`ToolOutputFiles`, the newest 50 kept; see [Tool output guardrails](internals/tool-output-limits.md#the-runners-cut-max_tool_output_chars)). Its keys are in [the Session file table](#session-file). A file from before `used_memory_names`, `preloaded_memory_names`, `muted_memory_names`, `parent_id` or `continues` reads those as empty lists, no parent and no previous link.
3
+ Sessions are plain files — no DB. Each session is `~/.local/state/samagotchi/sessions/<uuid>.json` (XDG-aware via `XDG_STATE_HOME`) plus a sidecar dir `<uuid>/` with `input/`/`notes/`/`output/`/`owner.lock`/`bridge.json` (`Session.session_dir`), `turn_drawings.jsonl` once a turn ended with a Bridge or in a one-shot run (each finished turn as live drew it, which the web's reload draws: [bridge.md](internals/bridge.md#turndrawings); a fork starts with its parent's lines for the turns its seed keeps unchanged, a continue with none: its turns, and any without a line, are drawn from their messages), and `tool_output/` once a long `execute` result was cut: its whole output, which the cut result names (`ToolOutputFiles`, the newest 50 kept; see [Tool output guardrails](internals/tool-output-limits.md#the-runners-cut-max_tool_output_chars)). Its keys are in [the Session file table](#session-file). A file from before `used_memory_names`, `preloaded_memory_names`, `muted_memory_names`, `parent_id` or `continues` reads those as empty lists, no parent and no previous link.
4
4
 
5
5
  **Message times:** an entry of `messages` may carry `at`, when it happened: a local-offset ISO time with milliseconds (`2026-10-24T14:32:05.120+02:00`). User prompts, lines merged into a turn and steers, reminders, context and task notes, and the model's replies have one (a note's is its `created_at`); tool results, `!cmd` messages and chi's own turn notes don't, nor does anything saved before chi stamped messages (no backfill). It is for the UIs only (the gap dividers, a bubble's time): it never goes to the model, so it changes nothing in the requests or their prompt cache. The one time the model reads is the reminders': due reminders go into a turn as a system message headed `[SYSTEM: REMINDERS DUE 2026-10-24 14:32 local]` (the turn's local time; `ReminderQueue#inject!`), written into the saved content then, so a later request sends the same text.
6
6
 
data/docs/testing.md CHANGED
@@ -180,7 +180,19 @@ Each level owns its own share; a detail is asserted once, at the lowest level th
180
180
  scenarios in `spec/shared/turn_drawings/` (written from `spec/support/turn_drawing_scenarios.rb`;
181
181
  `UPDATE_TURN_DRAWINGS=1 bundle exec rspec spec/bridge/turn_drawings_spec.rb spec/web/session_show_drawings_spec.rb`
182
182
  rewrites their lines and show after an intended change) feed `turn_drawing_parity.test.js`, which draws each one
183
- live (the real stream handlers and stage) and from its drawing and compares the shapes with no allow list. The
183
+ live (the real stream handlers and stage) and from its drawing and compares the shapes with no allow list.
184
+ `spec/shared/turn_ranges.json` (`UPDATE_TURN_RANGES=1 bundle exec rspec spec/bridge/turn_ranges_spec.rb`) pins
185
+ `Bridge::TurnRanges`' turns, their record pairing, the items as the show stamps them and each turn's drawing end;
186
+ timing.test.js checks `turnGroups` (stamps only) against it. Each scenario's
187
+ fixture also holds `synth`, the show drawn from `TurnDrawings::Synth`'s lines (written by
188
+ `spec/bridge/turn_drawings_synth_spec.rb`, which also compares each synth line with the live one minus
189
+ `Synth::LOSSES`); the parity test's synth arm draws it against live, each scenario naming the losses that change its
190
+ shape (`SYNTH_LOSSES_OF`). Rewrite the fixtures in this order after an intended change, each spec merging its own
191
+ keys: `UPDATE_TURN_DRAWINGS=1` over `spec/bridge/turn_drawings_spec.rb`, then `spec/web/session_show_drawings_spec.rb`,
192
+ then `spec/bridge/turn_drawings_synth_spec.rb`; `UPDATE_TURN_RANGES=1` over `spec/bridge/turn_ranges_spec.rb`. A
193
+ node test of a reloaded history feeds drawn input as the show sends it: `spec/web/public/drawn_history.js` stamps
194
+ its items into turns and gives each a minimal drawing (not the synthesizer: what a real drawing holds is the
195
+ fixtures'). The
184
196
  `lan` project's chi web is on the LAN only
185
197
  when the machine has a private IPv4: without one its LAN tests skip and the participant review journey runs on
186
198
  loopback.
@@ -6,6 +6,7 @@ require_relative "../atomic_file"
6
6
  require_relative "../events"
7
7
  require_relative "../state_format"
8
8
  require_relative "card_places"
9
+ require_relative "turn_notice"
9
10
 
10
11
  module Samagotchi
11
12
  class Bridge
@@ -68,15 +69,18 @@ module Samagotchi
68
69
  version: FORMAT_VERSION,
69
70
  members: [StateFormat.required(:type), StateFormat.extra(:extra, in_version: FORMAT_VERSION)]
70
71
  )
71
- NOTICE_TYPES = %i[hook_notice guardrail_warning empty_answer_retry steer_cut].freeze
72
+ # A question's events (TurnNotice's too): one :question entry, never
73
+ # pushed out while open.
74
+ QUESTION_EVENTS = %i[question_requested question_answered question_cancelled].freeze
72
75
  # Capped apart from the notices.
73
76
  LLM_CONTEXT_TYPES = %i[llm_context_edited].freeze
74
- LLM_CONTEXT_FIELDS = %i[type moment why freed_tokens tail_tokens staged text groups].freeze
77
+ # A turn's rows (TurnNotice::FIELDS, the fields a join replays them
78
+ # with) other than questions and ✂ rows, plus the load warnings.
79
+ NOTICE_TYPES = (TurnNotice::FIELDS.keys - QUESTION_EVENTS - LLM_CONTEXT_TYPES + %i[guardrail_warning]).freeze
75
80
  FILE = "cards.json"
76
81
  # The events after which the file is written again: the ones that
77
82
  # change an entry or the turn log.
78
- SAVED_ON = (%i[turn_started card hook_notice empty_answer_retry steer_cut llm_context_edited question_requested question_answered
79
- question_cancelled question_relay] + Events::TURN_END).freeze
83
+ SAVED_ON = (%i[turn_started card question_relay] + TurnNotice::FIELDS.keys + Events::TURN_END).uniq.freeze
80
84
  # What only the store reads: never listed.
81
85
  INTERNAL_FIELDS = %i[turn_id continued base_since past_idless after_opening during after_failed command].freeze
82
86
 
@@ -320,11 +324,8 @@ module Samagotchi
320
324
  # that turn: it anchors before the turn.
321
325
  when :guardrail_warning then push({ type: :guardrail_warning, message: event[:message], label: event[:label] }
322
326
  .compact.merge(in_turn: false, turn_id: @running_turn ? @turn_log[-2] : @turn_log.last))
323
- when :empty_answer_retry then add_turn_row(event.slice(:type, :attempt, :of, :stopped_by, :malformed)) if @running_turn
324
- when :steer_cut then add_turn_row(event.slice(:type, :source)) if @running_turn
325
- when :llm_context_edited then add_turn_row(Marshal.load(Marshal.dump(event.slice(*LLM_CONTEXT_FIELDS)))) if @running_turn
326
- when :question_requested
327
- add_turn_row({ type: :question, pending_question: Marshal.load(Marshal.dump(event[:pending_question])) }) if @running_turn
327
+ when :empty_answer_retry, :steer_cut, :llm_context_edited then add_turn_row(notice_row(event)) if @running_turn
328
+ when :question_requested then add_turn_row(notice_row(event).merge(type: :question)) if @running_turn
328
329
  when :question_answered then resolve_question(event[:id], answer: event[:answer])
329
330
  when :question_cancelled then resolve_question(event[:id], cancelled: true, reason: event[:reason])
330
331
  when :question_relay then mark_relay(event[:id], event[:relayed_to])
@@ -366,18 +367,27 @@ module Samagotchi
366
367
  # (a command's answer from another thread; a turn's proposal its own
367
368
  # button's command replaced, which nobody typed).
368
369
  old = @entries[index]
369
- @entries[index] = card.except(:command).merge(updated: true, **old.slice(:in_turn, :turn_id, :during, :continued, :base_since,
370
- :past_idless, :after_opening, :after_failed, :command))
370
+ # Its step too (iteration, calls): the first one's place, as live.
371
+ @entries[index] = card.except(:command).merge(updated: true, **old.slice(:in_turn, :turn_id, :iteration, :calls, :during, :continued,
372
+ :base_since, :past_idless, :after_opening, :after_failed,
373
+ :command))
371
374
  else
372
375
  entry = card.merge(in_turn: event[:in_turn] ? true : false, turn_id: anchor)
376
+ # The step it came in (a turn's row's place): where a drawing made
377
+ # from the turn's messages draws it (TurnDrawings::Synth).
378
+ entry.merge!({ iteration: @iteration, calls: @calls }.compact) if @running_turn && event[:in_turn]
373
379
  entry[:during] = true if @running_turn && !event[:in_turn]
374
380
  entry[:continued] = true if @running_turn && event[:in_turn] && @continuing
375
381
  push(entry)
376
382
  end
377
383
  end
378
384
 
385
+ # A TurnNotice event as the store keeps it: its FIELDS, deep-copied,
386
+ # and its type as a Symbol.
387
+ def notice_row(event) = TurnNotice.slice(event).merge(type: event[:type])
388
+
379
389
  def add_notice(event)
380
- notice = event.slice(:type, :hook, :text, :level, :fallback_for)
390
+ notice = notice_row(event)
381
391
  if event[:between_turns] || !@running_turn
382
392
  push(notice.merge(in_turn: false, turn_id: anchor))
383
393
  else
@@ -387,7 +397,7 @@ module Samagotchi
387
397
 
388
398
  # A row of the running turn's current step.
389
399
  def add_turn_row(row)
390
- entry = row.merge(in_turn: true, turn_id: @running_turn, iteration: @iteration, calls: @calls).compact
400
+ entry = row.merge(in_turn: true, turn_id: @running_turn, iteration: @iteration || row[:iteration], calls: @calls).compact
391
401
  entry[:continued] = true if @continuing
392
402
  push(entry)
393
403
  end
@@ -30,8 +30,12 @@ module Samagotchi
30
30
  # TurnDrawings#append). It runs under this accumulator's mutex and the
31
31
  # SessionObserver's lock: it must never call back in here. An error is
32
32
  # logged and the fold goes on.
33
+ # @param raise_errors [Boolean] a fold that raises raises out of #call
34
+ # (a drawing made from messages: TurnDrawings::Synth), never for a
35
+ # live turn's observer
33
36
  def initialize(max_output_chars: ToolOutputCut::WEB_PREVIEW_CHARS,
34
- clock: -> { Process.clock_gettime(Process::CLOCK_MONOTONIC) }, on_turn_end: nil)
37
+ clock: -> { Process.clock_gettime(Process::CLOCK_MONOTONIC) }, on_turn_end: nil, raise_errors: false)
38
+ @raise_errors = raise_errors
35
39
  @max_output_chars = max_output_chars
36
40
  @clock = clock
37
41
  @on_turn_end = on_turn_end
@@ -50,6 +54,8 @@ module Samagotchi
50
54
  def call(event)
51
55
  @mutex.synchronize { fold(event) }
52
56
  rescue StandardError
57
+ raise if @raise_errors
58
+
53
59
  nil # never break the running turn
54
60
  end
55
61