samagotchi 0.181.0 → 0.183.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 (200) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +93 -1
  3. data/bin/chi +4 -1
  4. data/docs/architecture.md +17 -7
  5. data/docs/bundle-authoring.md +1 -1
  6. data/docs/bundles.md +103 -4
  7. data/docs/cli.md +58 -10
  8. data/docs/configuration.md +3 -1
  9. data/docs/guardrails.md +16 -1
  10. data/docs/internals/block-renderers.md +172 -3
  11. data/docs/internals/bridge.md +23 -5
  12. data/docs/internals/bundles.md +21 -4
  13. data/docs/internals/engine.md +29 -8
  14. data/docs/internals/inline-widgets.md +3 -1
  15. data/docs/internals/prompt-caching.md +9 -1
  16. data/docs/internals/remote-sessions.md +38 -7
  17. data/docs/internals/web-frontend.md +116 -26
  18. data/docs/internals/working-set.md +1 -1
  19. data/docs/mcp-server.md +80 -0
  20. data/docs/plugins.md +308 -21
  21. data/docs/sessions.md +7 -4
  22. data/docs/sub-agent.md +9 -0
  23. data/docs/testing.md +3 -1
  24. data/docs/thin-clients.md +146 -0
  25. data/lib/samagotchi/answer_display.rb +3 -2
  26. data/lib/samagotchi/block_fix/stamp.rb +49 -0
  27. data/lib/samagotchi/block_fix.rb +220 -0
  28. data/lib/samagotchi/bridge/block_fix_route.rb +30 -0
  29. data/lib/samagotchi/bridge/pending_card.rb +4 -3
  30. data/lib/samagotchi/bridge/sse_writer.rb +16 -15
  31. data/lib/samagotchi/bridge/turn_drawings.rb +19 -0
  32. data/lib/samagotchi/bridge.rb +69 -69
  33. data/lib/samagotchi/bridge_client.rb +9 -0
  34. data/lib/samagotchi/bundle_command/api_calls.rb +1 -1
  35. data/lib/samagotchi/bundle_command/check.rb +36 -19
  36. data/lib/samagotchi/bundle_command.rb +50 -21
  37. data/lib/samagotchi/bundle_manifest.rb +101 -4
  38. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  39. data/lib/samagotchi/bundles/mcp/client.rb +260 -0
  40. data/lib/samagotchi/bundles/mcp/content.rb +107 -0
  41. data/lib/samagotchi/bundles/mcp/http_client.rb +407 -0
  42. data/lib/samagotchi/bundles/mcp/manifest.yml +13 -5
  43. data/lib/samagotchi/bundles/mcp/oauth.rb +814 -0
  44. data/lib/samagotchi/bundles/mcp/plugin.rb +556 -574
  45. data/lib/samagotchi/bundles/mcp/tools.rb +232 -0
  46. data/lib/samagotchi/bundles/system/config_modification_protocol.md +10 -2
  47. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  48. data/lib/samagotchi/cli/parent_wait.rb +5 -3
  49. data/lib/samagotchi/command_intake.rb +7 -0
  50. data/lib/samagotchi/commands/registry.rb +8 -3
  51. data/lib/samagotchi/config.rb +3 -0
  52. data/lib/samagotchi/continue_intent.rb +8 -0
  53. data/lib/samagotchi/continue_offer.rb +24 -15
  54. data/lib/samagotchi/engine/block_fix.rb +332 -0
  55. data/lib/samagotchi/engine/cards.rb +14 -5
  56. data/lib/samagotchi/engine/events.rb +10 -15
  57. data/lib/samagotchi/engine/models.rb +1 -1
  58. data/lib/samagotchi/engine/plugins.rb +3 -0
  59. data/lib/samagotchi/engine/recap.rb +1 -1
  60. data/lib/samagotchi/engine/side_requests.rb +8 -6
  61. data/lib/samagotchi/engine/sign_in.rb +142 -0
  62. data/lib/samagotchi/engine/turn_end.rb +3 -3
  63. data/lib/samagotchi/engine.rb +47 -27
  64. data/lib/samagotchi/engine_snapshots.rb +1 -1
  65. data/lib/samagotchi/events.rb +1 -0
  66. data/lib/samagotchi/guardrail_wiring.rb +3 -1
  67. data/lib/samagotchi/guardrails/protected_paths.rb +51 -2
  68. data/lib/samagotchi/guardrails/verdict.rb +3 -2
  69. data/lib/samagotchi/hold_stop.rb +4 -4
  70. data/lib/samagotchi/idle_client.rb +10 -6
  71. data/lib/samagotchi/idle_recap.rb +19 -11
  72. data/lib/samagotchi/idle_reminders.rb +7 -5
  73. data/lib/samagotchi/idle_scheduler.rb +7 -10
  74. data/lib/samagotchi/inline_widgets.rb +12 -0
  75. data/lib/samagotchi/installed_bundles/dir.rb +37 -0
  76. data/lib/samagotchi/installed_bundles/manifest.rb +7 -1
  77. data/lib/samagotchi/installed_bundles/plugin_ref.rb +9 -5
  78. data/lib/samagotchi/installed_bundles/record.rb +3 -2
  79. data/lib/samagotchi/installed_bundles/standing.rb +3 -1
  80. data/lib/samagotchi/kernel_loop.rb +7 -5
  81. data/lib/samagotchi/llm/chat_loop.rb +2 -0
  82. data/lib/samagotchi/llm/http.rb +96 -5
  83. data/lib/samagotchi/markdown_parser.rb +28 -0
  84. data/lib/samagotchi/mcp_command.rb +110 -0
  85. data/lib/samagotchi/mcp_server/http.rb +112 -0
  86. data/lib/samagotchi/mcp_server/protocol.rb +244 -0
  87. data/lib/samagotchi/mcp_server/stdio.rb +92 -0
  88. data/lib/samagotchi/mcp_server/text.rb +155 -0
  89. data/lib/samagotchi/mcp_server/tools.rb +245 -0
  90. data/lib/samagotchi/memory_bundle/asset_installer.rb +40 -12
  91. data/lib/samagotchi/memory_bundle/builder.rb +20 -2
  92. data/lib/samagotchi/memory_bundle/installed_copy.rb +1 -1
  93. data/lib/samagotchi/memory_bundle/installer.rb +16 -3
  94. data/lib/samagotchi/memory_bundle/provenance.rb +18 -1
  95. data/lib/samagotchi/memory_bundle/shas.rb +6 -4
  96. data/lib/samagotchi/memory_bundle/shipped_update.rb +7 -3
  97. data/lib/samagotchi/memory_bundle/status.rb +15 -6
  98. data/lib/samagotchi/memory_bundle/uninstaller.rb +9 -4
  99. data/lib/samagotchi/plugin/api.rb +6 -1
  100. data/lib/samagotchi/plugin/card.rb +36 -11
  101. data/lib/samagotchi/plugin/context.rb +63 -6
  102. data/lib/samagotchi/plugin/http.rb +40 -15
  103. data/lib/samagotchi/plugin/http_errors.rb +15 -0
  104. data/lib/samagotchi/plugin/http_stream.rb +86 -0
  105. data/lib/samagotchi/plugin/http_transport.rb +58 -16
  106. data/lib/samagotchi/plugin/loader.rb +18 -11
  107. data/lib/samagotchi/plugin/secrets.rb +266 -0
  108. data/lib/samagotchi/plugin/sign_in.rb +392 -0
  109. data/lib/samagotchi/plugin/sse_reader.rb +103 -0
  110. data/lib/samagotchi/queued_command.rb +28 -4
  111. data/lib/samagotchi/recap_setup.rb +13 -4
  112. data/lib/samagotchi/ref.rb +3 -2
  113. data/lib/samagotchi/relay_verifier.rb +8 -7
  114. data/lib/samagotchi/relay_watcher.rb +4 -4
  115. data/lib/samagotchi/run_options.rb +2 -1
  116. data/lib/samagotchi/send_command.rb +54 -41
  117. data/lib/samagotchi/session_access/ask.rb +244 -0
  118. data/lib/samagotchi/session_access/contract.rb +8 -0
  119. data/lib/samagotchi/session_access/delete_plan.rb +77 -0
  120. data/lib/samagotchi/session_access/exchange/token.rb +101 -0
  121. data/lib/samagotchi/session_access/exchange.rb +173 -0
  122. data/lib/samagotchi/session_access/local.rb +38 -6
  123. data/lib/samagotchi/session_access/remote.rb +23 -2
  124. data/lib/samagotchi/session_access.rb +1 -0
  125. data/lib/samagotchi/session_chain/delete.rb +39 -81
  126. data/lib/samagotchi/session_chain/delete_preview.rb +55 -19
  127. data/lib/samagotchi/session_command_catalog.rb +10 -0
  128. data/lib/samagotchi/session_commands.rb +17 -0
  129. data/lib/samagotchi/session_config.rb +4 -4
  130. data/lib/samagotchi/session_delete_command.rb +129 -3
  131. data/lib/samagotchi/session_manager/delegate_rule.rb +86 -0
  132. data/lib/samagotchi/session_manager/listing.rb +4 -4
  133. data/lib/samagotchi/session_manager/removal.rb +38 -12
  134. data/lib/samagotchi/session_manager/running_tasks.rb +50 -23
  135. data/lib/samagotchi/session_manager.rb +1 -0
  136. data/lib/samagotchi/session_observer.rb +27 -0
  137. data/lib/samagotchi/steer_cut.rb +4 -3
  138. data/lib/samagotchi/terminal_ui/attached_loop/sending.rb +4 -1
  139. data/lib/samagotchi/terminal_ui/formatting.rb +15 -0
  140. data/lib/samagotchi/testing/boundary.rb +4 -0
  141. data/lib/samagotchi/testing/bundle.rb +48 -2
  142. data/lib/samagotchi/testing/fake_http.rb +60 -15
  143. data/lib/samagotchi/testing/host.rb +4 -1
  144. data/lib/samagotchi/testing/recorder.rb +45 -5
  145. data/lib/samagotchi/tools/tool_index.rb +14 -3
  146. data/lib/samagotchi/version.rb +1 -1
  147. data/lib/samagotchi/web/app.rb +20 -6
  148. data/lib/samagotchi/web/ask_routes.rb +292 -0
  149. data/lib/samagotchi/web/block_fix_routes.rb +39 -0
  150. data/lib/samagotchi/web/markdown_renderer.rb +24 -9
  151. data/lib/samagotchi/web/mcp_route.rb +88 -0
  152. data/lib/samagotchi/web/message_display.rb +6 -1
  153. data/lib/samagotchi/web/participant_view.rb +1 -1
  154. data/lib/samagotchi/web/public/app.js +7 -8
  155. data/lib/samagotchi/web/public/block_fix.js +270 -0
  156. data/lib/samagotchi/web/public/block_fix_note.js +104 -0
  157. data/lib/samagotchi/web/public/block_frame.js +77 -13
  158. data/lib/samagotchi/web/public/block_host.js +45 -9
  159. data/lib/samagotchi/web/public/block_regions.js +126 -0
  160. data/lib/samagotchi/web/public/block_renderers.css +12 -0
  161. data/lib/samagotchi/web/public/block_watch.js +16 -2
  162. data/lib/samagotchi/web/public/card.js +22 -9
  163. data/lib/samagotchi/web/public/card_actions.js +21 -0
  164. data/lib/samagotchi/web/public/card_kinds.js +1 -1
  165. data/lib/samagotchi/web/public/card_registry.js +3 -2
  166. data/lib/samagotchi/web/public/data.js +15 -12
  167. data/lib/samagotchi/web/public/delete_sheet.js +222 -162
  168. data/lib/samagotchi/web/public/diagram_wiring.js +28 -0
  169. data/lib/samagotchi/web/public/format.js +3 -0
  170. data/lib/samagotchi/web/public/index.html +52 -7
  171. data/lib/samagotchi/web/public/inline_widgets.js +1 -1
  172. data/lib/samagotchi/web/public/more_sheet.js +6 -4
  173. data/lib/samagotchi/web/public/picture_regions.js +243 -0
  174. data/lib/samagotchi/web/public/picture_viewer.js +113 -12
  175. data/lib/samagotchi/web/public/refs.js +5 -3
  176. data/lib/samagotchi/web/public/region_hit.js +144 -0
  177. data/lib/samagotchi/web/public/removal_sheet_model.js +275 -0
  178. data/lib/samagotchi/web/public/running_tasks.js +6 -4
  179. data/lib/samagotchi/web/public/session_actions.js +105 -100
  180. data/lib/samagotchi/web/public/stream_handlers.js +5 -1
  181. data/lib/samagotchi/web/public/turn_block.js +5 -2
  182. data/lib/samagotchi/web/server.rb +6 -4
  183. data/lib/samagotchi/web/session_access_routes.rb +14 -11
  184. data/lib/samagotchi/web/session_control.rb +84 -30
  185. data/lib/samagotchi/web/session_create.rb +2 -2
  186. data/lib/samagotchi/worker/block_fixes.rb +22 -0
  187. data/lib/samagotchi/worker/child_side.rb +3 -2
  188. data/lib/samagotchi/worker/command_queue.rb +13 -13
  189. data/lib/samagotchi/worker/leave.rb +3 -3
  190. data/lib/samagotchi/worker/scratch.rb +6 -6
  191. data/lib/samagotchi/worker/signal_grace.rb +6 -5
  192. data/lib/samagotchi/worker/startup.rb +3 -3
  193. data/lib/samagotchi/worker/wake_turns.rb +4 -4
  194. data/lib/samagotchi/worker.rb +42 -24
  195. data/lib/samagotchi/worker_exit_claim.rb +1 -1
  196. data/lib/samagotchi/worker_idle_exit.rb +18 -9
  197. data/lib/samagotchi/worker_inbound.rb +12 -7
  198. data/lib/samagotchi/worker_participant_gate.rb +9 -7
  199. data/lib/samagotchi/worker_task_wakes.rb +7 -5
  200. metadata +42 -1
@@ -409,7 +409,8 @@ made in Keychain Access or by another app may raise an "allow access" dialog the
409
409
  deadline (or add `-T /usr/bin/security`). An unset key's error names the `security` command;
410
410
  `chi self` says `VAR (keychain)`, `chi desktop status` which keys the helper gets.
411
411
  `SAMAGOTCHI_KEYCHAIN=off` turns the Keychain off for a process and everything it starts (the spec suite sets it).
412
- Linux has no fallback: the variable only.
412
+ Linux has no fallback: the variable only. A bundle's own tokens (`ctx.secrets`, a sign-in's) aren't kept here but in
413
+ 0600 files under the state dir ([docs/plugins.md](plugins.md#secrets-ctxsecrets) says why).
413
414
 
414
415
  ### Anthropic Messages hosts
415
416
 
@@ -2405,6 +2406,7 @@ column says so, a `--kebab-name` flag. The maps (`hosts:`, `models:`,
2405
2406
  | `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). |
2406
2407
  | `web.stage_collapsed` | `false` | yes | Every session's stage in `chi web` starts folded to its status row (the running turn's prompt, steps and cloud behind ▴), a participant's page too. A session you fold or unfold by hand keeps its own fold in that browser (`chi_stage_collapsed:<session>`), whatever this says; one never touched follows it. Read when `chi web` starts: restart it after a change. |
2407
2408
  | `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`. The turn's own cards and questions are compared as data, apart from the history: what the page's stream said (`card_registry.js`) against what the read lists (CardStore), each card or question of this turn (`of_turn`) by its id, its kind, its status (answered, cancelled, still asking) and its summary line (a card's title); a difference counts as `card` or `question`. Bodies, buttons, folds, the tag a card is drawn in and where it sits are ignored (the history's compare leaves cards and questions out on both sides; their place is the specs'). A read that lists CardStore's cap of cards and questions may have lost an older one: a card the page has and such a read doesn't is no difference. A question the read gives no turn and no opening stamp for (an older worker) leaves the questions out. A page whose `app.js` is older than its `reload_check.js` (a mixed cache) compares no cards: its `reload_checked` line says `cards_compared: false`. Between-turn cards and notices stay with the e2e reload checks. Every open owner tab runs the check; `chi web` logs a turn's first report only, and starts over when it restarts. |
2409
+ | `web.block_fix` | `auto` | | `auto`: a fenced block the owner's page can't draw in the newest answer (a `chi-ui` picks or walk, a bundle's diagram such as Mermaid) is asked for again, once, as a side request (no turn, no message; it shows as `block-fix` in `/stats`' side line). The fixed block draws in place, with "Drawn after a fix" under it, and the saved answer holds it, so the model's next turn sees it too (or only the page, when a turn started meanwhile). A fix that doesn't draw either, an older answer, and the third block of an answer get an "Ask in chat" button that fills the composer. `off`: the block stays source under its error line, as before, and `POST /api/sessions/:id/blocks/fix` answers `404`. Read when `chi web` starts. See [block-renderers.md](internals/block-renderers.md#a-failed-block-is-asked-for-again). |
2408
2410
  | `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). |
2409
2411
  | `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). |
2410
2412
  | `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). |
data/docs/guardrails.md CHANGED
@@ -252,7 +252,8 @@ the user's alone (`user_only`): `chi answer` and the worker refuse the allow
252
252
  with `only the user can allow it`. The same holds for the guardrails bundle's
253
253
  other user-only rules (`chi-context-cmd`, `chi-broadcast`,
254
254
  `prompt-memory-write`, `model-overlay-write`, and `chi-answer-piped` /
255
- `chi-answer-http`, which answer a grandchild's question as the user).
255
+ `chi-answer-http`, which answer a grandchild's question as the user), and core's
256
+ `bundle-secrets-shell` (a command naming a bundle's secrets).
256
257
 
257
258
  `child-boundary` isn't one of them: an ask before a delegate child acts outside
258
259
  its folder follows the level, so a `soft` parent may give Allow once. If that
@@ -341,6 +342,20 @@ with `writes: true` (symlinks resolved; see
341
342
  `execute` can still reach them; the guardrails bundle asks about shell
342
343
  commands that name them.
343
344
 
345
+ A bundle's secrets ([`ctx.secrets`](plugins.md#secrets-ctxsecrets):
346
+ `<state dir>/plugins/<bundle>/secrets/`) are kept from chi's model whatever
347
+ the call does, reads too:
348
+
349
+ - deny (`bundle-secrets`): `read`, `write`, `edit` and a plugin tool's
350
+ `targets:` paths there (symlinks resolved);
351
+ - ask, once, the user only (`bundle-secrets-shell`, a protected rule): an
352
+ `execute` or `task_create` command that names the folder
353
+ (`…/samagotchi/plugins/<bundle or a glob>/secrets`, or this state dir's
354
+ path spelled out), `ls` and `cat` included.
355
+
356
+ It is an accident guard, not a sandbox: a command that doesn't name the
357
+ folder (one that `cd`s there first, a variable, a script) still reads it.
358
+
344
359
  ## A delegate child's boundary
345
360
 
346
361
  Built in, for [delegate](sessions.md#delegating) children only, in every
@@ -19,7 +19,7 @@ model. The TUI is untouched: it shows a fence as source.
19
19
  `renderer_changed`, each with its own reason. ETag + `no-cache`, as static files. A `block_renderers:` list that
20
20
  doesn't parse is logged once per bundle and problem (each list request and file fetch reads it); a bundle this chi is
21
21
  too old for (`requires_chi`) draws nothing, logged once per bundle and version (`block_renderers_too_new`).
22
- 3. `block_watch.js` (`createBlockWatch`, made by `block_host.js`'s `createBlockHost`, wired in `app.js`; a participant's page
22
+ 3. `block_watch.js` (`createBlockWatch`, made by `block_host.js`'s `createBlockHost`, wired by `diagram_wiring.js wireDiagrams` from `app.js`; a participant's page
23
23
  gets the core drawers only, no bundle's renderers: `block_renderers`) finds and watches the blocks; `block_host.js` is its frame drawer (`createFrameDrawer`). The watcher asks an
24
24
  ordered list of drawers, core ones first (`inline_widgets.js` for `chi-ui`: [inline-widgets.md](inline-widgets.md)), then the frame drawer, which waits for `/api/block_renderers`;
25
25
  the first that `claims` the block's language draws it, and a language none claims is left alone. The contract
@@ -35,7 +35,14 @@ model. The TUI is untouched: it shows a fence as source.
35
35
  4. `block_frame.js` (`createBlockFrame`): one hidden frame per language, made on first need, one render at a time, 15 s per
36
36
  call, the renderer files' fetch included (browser `fetch` has no timeout; a fetch past it is a failed load). A timeout, a
37
37
  dead frame or a session switch drops it, and a drop rejects whatever is pending, the load too. Handshake `loaded` → `code {files}` → `ready | failed`,
38
- then `render {id, source, theme}` → `done {id, svg} | error {id, message}`.
38
+ then `render {id, source, theme}` → `done {id, svg, regions?} | error {id, message, bundle?}`. The bootstrap's
39
+ `window.chi` is `{ defineRenderer, features: { regions: true } }`: a renderer returns the SVG, or `{ svg, regions }`
40
+ ([Regions](#regions)). An object without a string `svg` is the bundle's bug, `error {bundle: true}`: its
41
+ `FrameError` isn't `renderer`, so the block fails with its line and no fix is asked; a renderer that throws, or
42
+ returns no object at all (`undefined`, `null`, a number), is as before: a failed render that may be the model's
43
+ (a renderer can return nothing for a source it can't draw), so `renderer` and fixable. Kept so on purpose: the
44
+ bundle flag is for what only a bundle returns (an object), and a bundle's measuring stays inside its own `try`.
45
+ `createBlockFrame`'s `draw` resolves `{svg, regions}` (`render`, its SVG alone, stays); `block_host.js` uses `render` when a cached older `block_frame.js` has no `draw`.
39
46
  5. On success a `<figure class="block-drawn">` goes right before the `<pre>`, which stays in the DOM, `hidden`, so whatever
40
47
  reads text (copy, a claim's walk, fold thresholds) sees what it did. **The DOM is the state** (`block_source.js`): a Revise
41
48
  clone arrives with both. On failure the `<pre>` stays, marked `data-block-failed`, with one muted line: an attribute CSS
@@ -48,7 +55,9 @@ model. The TUI is untouched: it shows a fence as source.
48
55
  movable there; without `openPicture` (an older app.js) a click does nothing. The same is a `.block-zoom` button
49
56
  ("Open in the viewer": icon, `aria-label`) for the keyboard: before the toggle, shown on keyboard focus only, and
50
57
  taking no pointer while hidden; Esc in the viewer gives it the focus back.
51
- 6. Cache: a `Map` on `lang + theme + source`, about 200 entries, holding the `data:` URL; a later `bubble.innerHTML` wipes the
58
+ 6. Cache: a `Map` on `lang + theme + source`, about 200 entries, holding the `data:` URL and, when the renderer reported
59
+ some, the cleaned regions (so a cache hit, a Revise clone and a theme's redraw carry their own; a click finds the
60
+ entry by the `<img>`'s `src`, `pictureOfFigure`, at most 200 compares: an evicted entry gives the picture alone); a later `bubble.innerHTML` wipes the
52
61
  figure and the observer redraws in the same pass. No `crypto.subtle`: it's undefined on a plain-http LAN address. A system
53
62
  theme change redraws through the figure (a hidden `<pre>` never intersects).
54
63
  7. The view: a viewer at the bottom stays there (`scroll.js keepFollowing`); a block drawn above a reader's view keeps
@@ -63,6 +72,165 @@ model. The TUI is untouched: it shows a fence as source.
63
72
  `max-height` says the same number, a backstop whatever the parsing gets wrong. The decode is bounded too
64
73
  (15 s, the mark on until it ends). A very wide picture stays at least 120 px tall and scrolls sideways instead of a sliver.
65
74
 
75
+ ## Regions
76
+
77
+ A renderer may report where a diagram's parts are, so the picture viewer can make them tappable
78
+ ([web-frontend.md](web-frontend.md#picture-viewer)). What it returns beside its SVG, and what the page keeps:
79
+
80
+ ```js
81
+ { kind: "node" | "group" | "edge" | "note",
82
+ id: "BR", // the source's own name, text; "" when none
83
+ label: "Bridge", // what the picture shows, text; "" when none
84
+ box: [x, y, w, h], // fractions of the picture, 0..1; required but for an edge (its label's box)
85
+ points: [[x, y], …], // edge only: 2..16 points along its line
86
+ from: "BR", to: "EN" // edge only, optional: its ends' ids
87
+ }
88
+ ```
89
+
90
+ **Regions are untrusted**: the bundle is trusted, its input is model-written, and a renderer bug must not reach the
91
+ page or stall it. Two gates:
92
+
93
+ 1. **In the frame** (`BOOTSTRAP`): `regions` is sent only when it is an array of at most 600 (`MAX_REGIONS`); otherwise
94
+ the `done` carries none and nothing of it is cloned (a 2M-entry array took 0.4 s in Chromium and 1.4 s in WebKit to
95
+ post, on the page's thread). And what is posted is the frame's **bounded copy** of each entry: its known keys only,
96
+ strings cut to 200 characters (anything else `""`), a box only of 4, at most 16 points, numbers only (else `NaN`),
97
+ a non-object entry `null`; so nothing vast or uncloneable is ever cloned (600 regions with one-megabyte labels,
98
+ posted as they were, crashed a Chromium tab; copied, the render took 2.6 ms in Chromium and 1 ms in WebKit against
99
+ 0.2 and 0 without regions). Regions that throw when read (a proxy) are dropped, and a post that throws anyway is
100
+ sent again without them.
101
+ 2. **In the page**, `block_regions.js cleanRegions` (pure), before the picture is cached: not an array, or over 600 →
102
+ none; a running budget of 128 KB over the *cleaned* fields (kept strings' lengths, 12 per number), past it → none
103
+ (`MAX_REGION_BYTES`); an entry that isn't a plain object or whose `kind` isn't one of the four → skipped; `box`
104
+ exactly 4 finite numbers, clamped to 0..1 and cut to the picture, no area → skipped (an edge loses its box);
105
+ `points` 2..16 pairs of finite numbers, clamped, else the edge is skipped; `id`, `label`, `from`, `to` strings only
106
+ (never `String()` of an object), controls and line separators a space, bidi, zero-width and lone surrogates gone,
107
+ whitespace runs one space, cut by code points to 80 (`label` 120); only own keys of known names are read, and the
108
+ result is new objects. A region left with no name is skipped (a node, note or group with neither `label` nor
109
+ `id`; an edge with no `label` and not both ends): the card and a button name a region by the diagram's own text
110
+ only, and the page never makes one up (a "node 3" means nothing in the source, nor to the model). Nothing stringifies the raw data (structured clone keeps cycles and BigInt). A list dropped
111
+ whole is said once per language (`console.warn`, its count, no model text). **Never cut**: past a cap the picture
112
+ shows with nothing tappable.
113
+
114
+ **What the page does with a region's text: `textContent`, an `aria-label`, composer text. Never markup, a selector, a
115
+ URL, a `data-*` value another module reads back, or a key into an object.** Numbers become percent offsets in
116
+ `style` and the points of the page's own `<polyline>`, through lit bindings. Nothing reaches the server, a session
117
+ file, the DOM of an answer or the model. Cost: 1–2 ms per render in the frame (measuring is the bundle's), one
118
+ `cleanRegions` per render in the page, 1–4 KB a real diagram in the cache.
119
+
120
+ ## A failed block is asked for again
121
+
122
+ One mechanism for every drawn block, a `chi-ui` picks or walk (core's drawer) and a bundle's renderer (chi-mermaid's
123
+ `mermaid`): a block the owner's page can't draw **in the newest answer**, for a reason that is the model's (a refused
124
+ `chi-ui` block, a renderer's own `error`), is asked for once more as a side request, and the answer is patched. No
125
+ message is sent and no turn runs. `web.block_fix: off` ([configuration.md](../configuration.md)) is the page as before:
126
+ the web route answers `404` instead of relaying a block fix.
127
+
128
+ ```
129
+ page: a drawer fails a block in the newest answer, marked fixable
130
+ └─ POST /api/sessions/:id/blocks/fix {turn_id, lang, source, reason} (chi web, :owner: Web::BlockFixRoutes)
131
+ → Bridge POST /session/:id/blocks/fix (Bridge::BlockFixRoute) → Engine#fix_block
132
+ ├─ the answer's stamp knows this block → 200 {state: "fixed" | "failed"}
133
+ └─ else 202 {state: "running"}; a side thread asks the model, checks the answer,
134
+ queues the result and wakes the worker's loop
135
+ worker loop, between turns (before any queued prompt): Engine#apply_block_fixes
136
+ └─ patches the answer (its text, or its display), stamps it, saves, announces :block_fix
137
+ page: on :block_fix → re-reads that answer; the patched block draws as any block
138
+ reload: the answer is the patched text; the render marks the block from the stamp
139
+ ```
140
+
141
+ **The request** (`BlockFix.request`, `Engine::BlockFixPart`): `ask_side_model`, as `/btw` and ctx.ask_model, on the
142
+ session's model: the conversation up to and including the answer as the side transcript (`Plugin::SideQuestion`, its
143
+ last 32,000 characters; display-only keys gone), then the failed block, its language and its error (cut to 300
144
+ characters, in the user part only). `BlockFix::SYSTEM` asks for the corrected block only, in one fence; for `chi-ui` the
145
+ schemas follow (`InlineWidgets::FIX_RULES`: core can't read the inline-widgets bundle's prompt sections). No tools,
146
+ thinking off, 25 s, 6,000 tokens out. It shows as `block-fix` in `/stats`' side line, always the owner's.
147
+ `BlockFix.extract` takes the first fence of the answer (else the whole answer); it is refused when the answer was cut
148
+ off at its limit, empty, the same block, or over 16 KB, and a `chi-ui` fix must parse (`BlockFix.check`). Any other
149
+ language passes: only the page can draw it.
150
+
151
+ **Where the block is** (`BlockFix.locate`, `locate_all`, `replace`, `replace_all`): commonmarker, the page's render's
152
+ parser (`MarkdownParser` loads it for the render and the worker), walks the `code_block` nodes; each in that language
153
+ whose normalised source is the block's is a copy of it (an answer may repeat a block: a fix patches every copy, so none
154
+ is left to fail and be asked for again), and its `source_position` gives its body's lines. `replace` keeps the fence lines and gives each
155
+ new line the old body's indent (a list item's) and the text's own line ends. A block in a blockquote isn't fixed (its
156
+ lines carry `> `). A block's identity is `BlockFix.key`: SHA-256 of the language and the normalised source, 32 hex
157
+ characters.
158
+
159
+ **The route's answers** (`Engine#fix_block`): 409 `fix_unavailable` (no session, a scratch one, no commonmarker), 413
160
+ `block_too_large` (over 16 KB), then the turn's answer (`AnswerTail.find` by turn id; none: 409 `block_not_found`) and
161
+ **its stamp before its text**: 200 with the stamp's state when the stamp knows the block, even when the block is no
162
+ longer in the answer (a page that drew the answer before its fix, a second tab: `fixed`, and it reads the answer
163
+ again); a block that is a fix and fails again, or a `fixed` block still in the shown text (a copy no fix reached),
164
+ answers `failed`, never `fixed`, so a page can't redraw and ask again. Then 409 `block_not_found` (the source isn't a
165
+ block of the answer), 202 `running` while that answer's block is asked (in flight per answer and block: the same block
166
+ in a newer answer is that answer's own ask), 429 `fix_limit` past 2 blocks of one answer (`BlockFix::PER_ANSWER`: its
167
+ stamp and its asks in flight or waiting, so a reload's page can't ask for a third), 429 `fix_busy` past 2 in flight
168
+ (`MAX_RUNNING`). The answer is resolved once, there: the result carries its **anchor** (its index in the conversation, its digest as `Bridge::TurnDrawings`
169
+ computes one, and the turn counter: `Engine#turn_messages` counts each turn).
170
+
171
+ **The write: on the worker's loop, between turns, never from the request's thread.** A running turn holds its own copy
172
+ of the conversation and writes it back at its end. `Worker::BlockFixesPart#apply_block_fixes` runs in each pass that
173
+ runs the queued commands, after them and before the notes and the next prompt (the idle pass and each input file's
174
+ step); the result's thread wakes the loop (`Engine#block_fix_ready=`, `Waker#wake`). Under the event lock, four
175
+ outcomes:
176
+
177
+ - **No turn started since the ask, and the answer is still the newest** (`AnswerTail.find`; notes, a `!cmd` line and
178
+ `/continue no` land after an answer without a request, so "the last message" isn't the test): its `content` is
179
+ patched, its `display` too when a hook set one, and on `api: anthropic` its saved blocks (`anthropic_content`, which
180
+ `AnthropicWire#assistant_blocks` sends as they are): the text block that holds the block whole, else the blocks are
181
+ dropped and the answer goes as its text. A thinking block is never touched (with the blocks dropped, the answer's
182
+ thinking blocks go with them: the `thinking` text stays on the message, a final answer with no `tool_use` is valid
183
+ without them, and `ReasoningHistory.earlier_thought?` reads `thinking` too). The next turn sends the patched answer.
184
+ A fix asked as its own turn ends (the page asks on the end event, before the turn's hooks are done) counts as no turn
185
+ since.
186
+ - **A turn started since** (or was running at the ask): only `display` (`AnswerDisplay::KEY`, what the page renders in
187
+ place of `content`; never sent to a model). No message a model has been sent is rewritten, so no prompt cache is
188
+ invalidated.
189
+ - **The answer is still there but the fix can't land** (the block left its shown text, say a hook's new display; or the
190
+ patched display would pass `AnswerDisplay::MAX_CHARS`, on either path): the block is stamped `failed` with the
191
+ reason ("the answer changed", "the fix is too long"), so a reload doesn't ask again.
192
+ - **The answer is gone** (its digest changed: a rollback, a new text; the turn id now names another answer: a reminder
193
+ turn's id names no prompt, so it falls back to the newest answer): the fix is dropped (`state: "dropped"`), no stamp.
194
+
195
+ A fix in an answer's text moves its digest; the engine keeps the move (`@block_fix_moved`), so the answer's other
196
+ block, asked before that fix landed, still finds its answer (and its event's `was_digest` is the digest it patched).
197
+ The move map is capped at `MOVED_DIGEST_LIMIT = 64`: the oldest move is evicted, so a fix landed after 64 later
198
+ text-changing moves no longer finds and patches the older answer.
199
+
200
+ A failed ask stamps the answer only. Each outcome is one `Log.info(:model, "block_fix_<state>", lang:, key:, bytes:, ms:,
201
+ landed:, reason:)` line (never the source) and one `:block_fix` event (`turn_id`, `key`, `lang`, `state`, `landed`,
202
+ `reason`, and the answer's digest before and after: `was_digest`, `digest`). A participant never gets it
203
+ (`ParticipantView::DROPPED`). A pending result doesn't keep a worker alive: an idle exit or a stop loses it, and the
204
+ page's give-up shows "Ask in chat".
205
+
206
+ **The stamp** (`BlockFix::STAMP`, `block_fixes` on the answer's model message: `{key, fixed_key, state, reason, at}`
207
+ per block asked) is display only (`AnswerDisplay::DISPLAY_ONLY`) and rides both loops' allowlists (`ChatLoop#plain`,
208
+ `KernelLoop#sanitize_history`). It is why nothing is asked twice: a reload, a second tab and a re-rendered bubble get the
209
+ stamp's answer. `Web::MarkdownRenderer#render(block_fixes:)`, from `MessageDisplay`'s answer render only, marks a block
210
+ that is a fix `data-block-fixed` and one whose fix failed `data-block-fix-failed`; an unstamped answer's HTML is as
211
+ before.
212
+
213
+ **The page** (`block_fix.js`, `block_fix_note.js`; [web-frontend.md](web-frontend.md#a-failed-block-asked-for-again)):
214
+ a block failed by the model's input (a refused `chi-ui` block, a renderer's own `error`: `FrameError.renderer`) is
215
+ marked fixable; a failure that isn't the model's (the renderer didn't load, a hang, a timeout, over 64 KB, a picture
216
+ too large) keeps today's line, with no button. In the newest answer the line reads "· asking for a fix…" with a
217
+ pulsing dot; the fixed block draws as any block, with "Drawn after a fix" under it. A fix that didn't help says so
218
+ with an **Ask in chat** button (it fills the composer with "The X block in your answer didn't draw: reason. Please
219
+ send it again, corrected."; never sends), as does an older answer's failed block and an answer's third. A live worker
220
+ without the feature (`workerPredates`, with the store's `bridgeUp`): "· restart this session to fix"; a worker that
221
+ isn't up is asked, and chi web's 503 `not_live` gives the plain line. An answer is read again at most once per block
222
+ for the page's life, so a copy still failing after the redraw says a fix didn't help. The terminal and a participant's page show nothing new.
223
+
224
+ **The turn's drawing.** A patched `content` changes the digest the turn's drawing line ends on (`TurnDrawings#holds?`),
225
+ so the Bridge's `TurnDrawings` (an observer of `:block_fix` with `landed: "answer"`) writes that turn's line again with
226
+ the new end digest, when the old one ended on the answer as it was (`was_digest`). A `display` patch keeps the digest.
227
+
228
+ **What a content patch costs**: nothing on a remote prefix cache or on Anthropic's Messages API (the cached prefix ends
229
+ before the answer); on llama.cpp the slot re-evaluates from the patched block, a few hundred tokens, and the turn-end
230
+ warm-up's gain is lost for that one turn ([prompt-caching.md](prompt-caching.md#the-turn-end-warm-up)). A `!rollback` or
231
+ a canceled Continue can restore a checkpoint from before the patch: the answer comes back unpatched and unstamped and may
232
+ be asked for once more.
233
+
66
234
  ## Security model
67
235
 
68
236
  The bundle's JS is trusted (installing a bundle already means trusting it, [plugins.md](../plugins.md#trust)). **Its input
@@ -75,6 +243,7 @@ is model-written**, so a renderer bug or an injected diagram must not reach a pa
75
243
  | Page header `frame-src 'none'` (`App::FRAME_HEADERS`; srcdoc frames still load and run under it) | self-navigation, meta refresh, anchor click, which leak past the frame's CSP in both browsers |
76
244
  | `delete window.RTCPeerConnection` + `webkitRTCPeerConnection` in the bootstrap, before any bundle code | the plain WebRTC call only |
77
245
  | Output only as `<img src="data:…">` | scripts and remote images inside the SVG don't run or load |
246
+ | Regions capped in the frame, cleaned in the page (`block_regions.js`), used as text and numbers only | a renderer's regions as markup, a selector or a URL; a vast or uncloneable list stalling the page |
78
247
 
79
248
  **Hard rules.**
80
249
 
@@ -5,12 +5,19 @@ localhost HTTP server in the worker's process, next to the `Engine` it reads and
5
5
  terminal are its clients; no browser reaches it. [architecture.md](../architecture.md) places it among the layers;
6
6
  this page is the surface: what it keeps, how a client joins and catches up, and every route.
7
7
 
8
- Bridge Engine calls are listed with their reasons in `Bridge::ENGINE_CALLS`; add each new Engine call there.
8
+ Bridge Engine calls are listed with their reasons in `Bridge::ENGINE_CALLS`; add each new Engine call there. Four of
9
+ the Engine's parts are not among them: `Bridge.new` takes them as `event_log:`, `turn_state:`, `question_desk:` and
10
+ `steer_cut:` (the Engine's own `SessionObserver`, `TurnState`, `QuestionDesk` and `SteerCut`: `Engine#event_log`,
11
+ `#turn_state`, `#question_desk`, `#steer_cut`, handed on by the Worker) and calls them directly: `subscribe`,
12
+ `unsubscribe`, `event_count`, `announce` and `synchronize` on the log; `running?`, `controller`, `cancel!` and the
13
+ enqueued-id ledger on the turn state; `pending`, `answer`, `cancel` and `annotate` on the desk; `input_epoch`,
14
+ `cut_for_steer` and `generation_snapshot` on the cut. `ENGINE_CALLS` lists what is left.
9
15
 
10
16
  ## What a Bridge keeps
11
17
 
12
- `Bridge#start` binds a port (OS-assigned, `127.0.0.1`), then subscribes four persistent observers to the Engine
13
- (`Engine#subscribe`, the thread-safe fan-out whose events all carry a monotonic `event_seq`). Each is cheap and
18
+ `Bridge#start` binds a port (OS-assigned, `127.0.0.1`), then subscribes five persistent observers to the event log
19
+ (`SessionObserver#subscribe`, the thread-safe fan-out whose events all carry a monotonic `event_seq`): the capture
20
+ observer (feeding the ring), the accumulator, the drawings, the cards and the pending card. Each is cheap and
14
21
  rescues its own errors: an observer must never break the running turn.
15
22
 
16
23
  | Piece | File (`bridge/`) | Holds |
@@ -265,7 +272,8 @@ the "asking again" and steer-cut rows, ✂ rows and questions (with how they wer
265
272
 
266
273
  ## SSEWriter
267
274
 
268
- One per `GET /session/:id/stream` connection, and itself that connection's observer: `Engine#emit_event` calls
275
+ One per `GET /session/:id/stream` connection, and itself that connection's observer (it takes the event log, no
276
+ Engine): `Engine#emit_event` calls
269
277
  `#call` on the turn's thread, so it only pushes onto a `BoundedQueue` (when full, the oldest entry goes and an
270
278
  overflow flag is set). The connection's own thread (`#serve!`) drains the queue onto the socket, so a slow client
271
279
  cannot stall a turn or another subscriber. An event holding bytes JSON can't take goes out scrubbed
@@ -278,7 +286,7 @@ ring holds the event. `serve!` orders a join so that nothing is missed or double
278
286
  4. drain the queue for `seq > snapshot`; a per-connection high-water mark drops what step 3 already wrote.
279
287
 
280
288
  `?snapshot=1` replaces 2-3: subscribe and `Bridge#snapshot_frame` happen as one step with the event log held
281
- (`Engine#synchronize_events`), the client gets one `snapshot` frame, and live events follow from the next seq.
289
+ (`SessionObserver#synchronize`), the client gets one `snapshot` frame, and live events follow from the next seq.
282
290
 
283
291
  A **`reset`** frame (the same content, numbered with its own seq) is written when a cursor cannot be replayed: it is
284
292
  from another epoch, ahead of the engine (a restarted worker), behind the ring's window (a cursor at `oldest - 1` has
@@ -426,6 +434,15 @@ The Bridge exposes:
426
434
  `200`, or `409` when it is no longer pending.
427
435
  - `POST /session/:id/guardrails/wrong` — `{id}`: label this session's System 1 auto-allow as
428
436
  one it should have asked about; `200`, `404` for an unknown judgment, `409` if already labelled.
437
+ - `POST /session/:id/blocks/fix` — `{turn_id, lang, source, reason}`: ask again, once, for a block the owner's page
438
+ couldn't draw in that turn's answer (`Bridge::BlockFixRoute` → `Engine#fix_block`; web route `POST
439
+ /api/sessions/:id/blocks/fix`, `Web::BlockFixRoutes`). `400 missing_fields` without a turn id, a fence language
440
+ (`BlockRenderers::LANG`) or a source, or `400 invalid_json` for a non-object body; `200 {state: "fixed" | "failed",
441
+ reason?}` when the answer's stamp knows the block, `202 {state: "running"}` while it is asked,
442
+ `404` for a worker or web route whose `block_fix` feature is off, `409 fix_unavailable` / `block_not_found`,
443
+ `413 block_too_large`, `429 fix_limit` / `fix_busy`. The result lands between turns and is announced as `:block_fix` (a `state` event; never a
444
+ participant's); a fix that patched the answer's text writes its turn's drawing line again with the new end digest
445
+ (`TurnDrawings#call`). See [block-renderers.md](block-renderers.md#a-failed-block-is-asked-for-again).
429
446
  - `POST /session/:id/holds/stop` — stop those holds without the worker leaving; `200 {status: "stopped",
430
447
  session_id, stopped}` or `501 holds_unavailable`.
431
448
  - `POST /session/:id/tasks/stop` — `{task_id}`: stop a background task as the user
@@ -666,6 +683,7 @@ compatibility from its version. `Bridge::FEATURES` advertises:
666
683
  | `cancel_turn_id` | `POST /session/:id/cancel` can stop only the named turn. |
667
684
  | `participant_revise` | chi web can pass a participant's Revise draft for worker-side validation. |
668
685
  | `participant_client_id` | chi web can identify a participant as `participant:<id>` instead of using the legacy `review:<id>`. |
686
+ | `block_fix` | `POST /session/:id/blocks/fix` asks again for a block the page couldn't draw; the owner's page without it says "restart this session to fix". |
669
687
  | `working_set_item` | `GET /session/:id/working_set/item` answers one item's timeline (the running turn's mid-turn), so chi web asks for it instead of the whole snapshot. |
670
688
 
671
689
  `chi web`'s `GET /api/sessions/:id/stream` proxies this bridge
@@ -41,7 +41,7 @@ read side, never the reverse.
41
41
  | Piece | Role |
42
42
  |---|---|
43
43
  | `InstalledBundles` (`installed_bundles.rb`) | `.each(holding:, dir:)` (each installed bundle by name, its `Record`; one whose `manifest.json` doesn't read with `error` set, and with `holding:` only those with that key, or that dir when it doesn't read), `.claimants` (which bundles own a memory file), `.dir` (`MemoryPaths.bundles_dir`) |
44
- | `InstalledBundles::Dir` (installed_bundles/dir.rb) | one bundle's `.bundles/<name>/` as the runtime reads it: `Dir.new(name:, dir:)`, `#record`, `#plugin_dir`, `#plugin_path`, `#scripts_dir`, `#guardrails_dir`, `#kept_manifest_path`, `#file_refusal(kind, file, recorded)` (the one "is this installed file as installed" check: `:plugin`, `:scripts`, `:guardrails`, one order (no sha recorded, missing, changed) and one wording, `bundle X's <folder>/<file> isn't recorded / is missing / differs from the installed one (reinstall the bundle)`, a `Refusal`). Its only state is the name and the folder; `Provenance` is one |
44
+ | `InstalledBundles::Dir` (installed_bundles/dir.rb) | one bundle's `.bundles/<name>/` as the runtime reads it: `Dir.new(name:, dir:)`, `#record`, `#plugin_dir`, `#plugin_path`, `#scripts_dir`, `#guardrails_dir`, `#kept_manifest_path`, `#plugin_part_paths`, `#plugin_refusal(record)` (the whole plugin: the file's `file_refusal`, then each part's in load order, then `:parts_missing`, below; the loader, `Status.plugin_status` and `SessionConfig#unloadable` ask it), `#file_refusal(kind, file, recorded)` (the one "is this installed file as installed" check: `:plugin`, `:scripts`, `:guardrails`, one order (no sha recorded, missing, changed) and one wording, `bundle X's <folder>/<file> isn't recorded / is missing / differs from the installed one (reinstall the bundle)`, a `Refusal`). Its only state is the name and the folder; `Provenance` is one |
45
45
  | `InstalledBundles::Standing`, `Refusal` (installed_bundles/standing.rb) | the usability verdict: `.standings(holding:, dir:)` (the walk, each bundle's `Standing`), `.standing(name, dir:)` (one record; a `manifest.json` that doesn't parse is `:unreadable`, in the walk's words), `Standing.of(name, record)`: `#refusal` is `:unreadable` (the record; `Standing.warn_unreadable` logs `bundle_unreadable` once per process per bundle and reason, whichever reader came across it, `.claimants` too) or `:too_new` (requires_chi), nil when chi may use it; none of the bundle's own files is hashed (a manifest cache miss hashes the kept `manifest.yml`, as `Manifest.of` does). A `Refusal` has `kind`, `text` and, for `:file_changed`, the `actual` and `expected` shas. Each reader keeps only its reaction (below) |
46
46
  | `InstalledBundles::Sha` (installed_bundles/sha.rb) | the record's shas: `.recorded` (either format, `""` for none), `.of_file`, `DEV` (a dev install's `sha256:dev`), `.unchecked?`, `.matches?` |
47
47
  | `BundleCommand` (`lib/samagotchi/bundle_command.rb`) | `chi bundle install/upgrade/uninstall/status/diff/list/build/trash/new/test/check/try` (`install --dev`: the Installer's `dev:`, links and `InstalledBundles::Sha::DEV`); runs the Installer, prints its summary, runs the conflict agent step; refuses a source already installed under another name (`installed_under_another_name?`: a git URL bundle recorded under its repo's name before the manifest named it). `upgrade` resolves its argument by `upgrade_source`: a git URL or an existing path, then a shipped name, then the bare name of an installed bundle — whose record's source it then uses (a git URL with its `#ref`, a dir or an archive that is still there), printed as `Upgrading NAME from SOURCE`; a dev record is refused with `Installer.dev_install_line`, a recorded source that is relative, empty or gone says so and asks for the path or URL of a copy (`Installer.source_gone_line`, the words `ManifestStanding` uses too). After an upgrade or uninstall that changed the bundle's plugin (or brought one in), one line names the sessions still running its old code (`LiveVersions.workers`, the ones whose worker takes a restart) and `chi sessions restart ID` for each: only the plugin stays in memory, since a bundle's rules reload by their stamp and its scripts run from the replaced files. |
@@ -50,7 +50,7 @@ read side, never the reverse.
50
50
  | `BundleCommand::ApiCalls` (bundle_command/api_calls.rb) | what a plugin's source calls of the API, by Prism: `#findings` (a call or keyword the API's classes lack, `check`'s `api`), `#keywords` (the floor check's `call(keyword:)`). Its only list is `MEMBERS`, which object a member gives (`ctx.sessions` → `Plugin::Sessions`); a new such object joins it |
51
51
  | `BundleCommand::Scaffold` (bundle_command/scaffold.rb) | `chi bundle new NAME`: the starting files (block-form `plugin:` entry, `requires_chi` at this chi, a kit test that passes as written); the manifest's shas are filled through `Shas.refresh` |
52
52
  | `BundleCommand::TestRun` (bundle_command/test_run.rb) | `chi bundle test`: `RbConfig.ruby -I <chi's lib>` on `test/**/*_test.rb` (Minitest) or `spec/` (RSpec, as `rake bundles:specs`), under `Bundler.with_unbundled_env` when Bundler's runtime is loaded |
53
- | `Shas` (shas.rb) | a manifest's `sha256:` lines: `.refresh(dir[, text])` rewrites them line by line (the layout kept; a `files:` entry it can't place raises `Shas::Error`), `.stale` → `[Stale(file, old, new)]` (`old` `""` for a placeholder, nil for a plugin / script entry with no sha line), `.parseable` (a placeholder `sha256: sha256:` isn't YAML). Plain Ruby: `rake bundles:sha` / `bundles:check` (`script/release/release_tools.rb`) and `chi bundle check --fix` share it |
53
+ | `Shas` (shas.rb) | a manifest's `sha256:` lines (a plugin part's is a four-space `name.rb: sha256:<hex>` line under `plugin:` `parts:`, the file being the part's name in the bundle dir): `.refresh(dir[, text])` rewrites them line by line (the layout kept; a `files:` entry it can't place raises `Shas::Error`), `.stale` → `[Stale(file, old, new)]` (`old` `""` for a placeholder, nil for a plugin / script entry with no sha line), `.parseable` (a placeholder `sha256: sha256:` isn't YAML). Plain Ruby: `rake bundles:sha` / `bundles:check` (`script/release/release_tools.rb`) and `chi bundle check --fix` share it |
54
54
  | `InstalledBundles::FileDigest` (installed_bundles/file_digest.rb) | the one digest of a file on disk: `.hex(path)` (its bytes, streamed; nil when the path isn't a file, a raise for one that can't be read), `.sha256(path)` = `"sha256:<hex>"`, nil with no file — the shape a record writes for a rule, plugin or script. `InstalledBundles::Sha.of_file`, `Merger.digest`, `Status.checksum`, `InstalledBundles::Record#source_sha`, `FileStanding.differs?` and the Installer's checksum verifiers all go through it; a digest of bytes already in memory (a merge's text, a memory's content that is also its base) stays with the code holding them |
55
55
  | `SourceNormalizer` (source.rb) | source → local dir; a git/zip/tar extract is *owned* and removed after the install |
56
56
  | `SourceIdentity` (source.rb) | what a source is, for comparing two installs of one name: `shipped:<dir>` (any gem or checkout), `git:<url>` (no `#ref`, trailing `/` or `.git`), `path:<realpath>`; nil when it can't place one |
@@ -126,9 +126,10 @@ A guardrail plugin (`plugin:` `required: true`) is known from `InstalledBundles:
126
126
  unparsable kept manifest.yml never drops it (an older chi's `PluginRef` ignores the key):
127
127
  its failure goes to the hook failures as required (`ExtensionLoad#load_plugins` passes them as `guardrail_failures:`),
128
128
  where the gate denies every tool call; a `chi.on(on_error: :fail_closed)` hook is wrapped `Hooks.wrap(policy: :deny)`.
129
- `Plugin::Loader.load_bundle` asks the verdict (`InstalledBundles::Standing`, then `Dir#file_refusal(:plugin, …)`) and reacts (`.namespace_for` is the bundle's
129
+ `Plugin::Loader.load_bundle` asks the verdict (`InstalledBundles::Standing`, then `Dir#plugin_refusal`) and reacts (`.namespace_for` is the bundle's
130
130
  `Samagotchi::Bundles::<bundle>` module); the loading itself is `Plugin::Loader.register_file` (one
131
- plugin file: build, `register`, `commit!`), which raises instead of logging: the bundle test kit
131
+ plugin: its `parts:` `module_eval`'d in order, each with its own path, then the file, into one fresh module; build,
132
+ `register`, `commit!`), which raises instead of logging: the bundle test kit
132
133
  (`Samagotchi::Testing::Bundle`) loads a bundle's source through them, unchecked. `Samagotchi::Testing::Install` is the
133
134
  checked path in a sandbox: the Installer, then `ExtensionLoad` (config hooks, then `load_plugins`), returning the
134
135
  Installer's warnings, this bundle's load failures and what it registered (`Install.registered`, an `Install::Registered` value, also the parity
@@ -136,6 +137,22 @@ spec's shape). A load failure carries `LoadFailures::Failure#location` (the firs
136
137
  bundle, or a SyntaxError's own line), which `Install` maps from the installed copy (`.bundles/<name>/plugin/`)
137
138
  back to the source dir.
138
139
 
140
+ Plugin parts (`plugin:` `parts:`, docs/plugins.md "A plugin in several files"). `BundleManifest#plugin_files` is the
141
+ one ordered list (parts as listed, then the file; nothing sorts it: not the parser, `Provenance#write` or the
142
+ builder). The record keeps them under its plugin, `{"file": …, "sha256": …, "parts": {"client.rb": "sha256:…"}}`
143
+ (`PluginRef#parts`, `{}` without; `Record#plugin_shas` has every file, so `AssetInstaller`, the `Uninstaller` and
144
+ `ShippedUpdate#trash_bound` treat parts as recorded files), each with a base at `bases/plugin/<part>`.
145
+ `BundleManifest::SINCE` has `"plugin.parts"` (the Unreleased comment until `release:bump`). What other chis do:
146
+ - The previous release ignores `parts:` in a manifest and in a record. It installs a too-new plugin with only a
147
+ warning, copying the plugin file alone; after `chi update` this chi refuses that record: `Dir#plugin_refusal`'s
148
+ `:parts_missing` (`bundle X's plugin parts aren't installed (reinstall the bundle)`, status `[parts missing]`), read
149
+ from `InstalledBundles::Manifest#plugin_parts` (the kept manifest's part names, the record's when it isn't read: no
150
+ kept file, or an edited one, is no refusal of this kind).
151
+ - On its own uninstall or upgrade of a record with parts, the parts in `plugin/` are files its record doesn't name:
152
+ `AssetState.in` lists every file in the folder, so they count as edited, get a copy in the trash, and go with the
153
+ folder. Harmless.
154
+ - This chi reads an older record with no `parts` key as no parts: nothing to migrate.
155
+
139
156
  Class-file hooks (retired). A record an older chi installed may still have a `hooks` map and `hooks/*.rb`
140
157
  (`InstalledBundles::Record#hooks`). Nothing loads them, and nothing announces them any more (the first turn, `chi bundle
141
158
  status` and `chi update` did from 0.158 to 0.166). A source with
@@ -124,7 +124,7 @@ Interrupt (Ctrl-C; a one-shot only, a worker traps INT):
124
124
  interrupted result (ToolResponse.run_batch), so no call is kept without its result; a half-streamed reply is
125
125
  not kept; :turn_canceled {cancellation_reason: :ctrl_c}; re-raised (the caller decides whether to exit)
126
126
 
127
- A Stop (Engine#cancel_current_turn!, the Bridge's POST cancel) or a hook's stop_turn:
127
+ A Stop (TurnState#cancel!: the Bridge's POST cancel, Engine#cancel_current_turn!) or a hook's stop_turn:
128
128
  → not an error: LLM::ModelResult(canceled: true, conversation:); complete_turn keeps the conversation with a
129
129
  TurnNote.cancelled note; text streamed before the cancel stays, marked [interrupted]
130
130
 
@@ -331,7 +331,12 @@ only input (`entries`, `reachable_names`, `left_out_names`, `removed_names`, `st
331
331
  One object (`turn_state.rb`), guarded by a `Monitor`, that the turn thread writes (`begin_turn`, `release_turn`)
332
332
  and other threads read: the idle scheduler, the Bridge's request threads, plugin threads, the UIs. It holds
333
333
  running, `context` (nil between turns), `last_context`, `controller`, the turn's thread and `ended`, the sink,
334
- steers and carried steers, and the activity clock.
334
+ steers and carried steers, and the activity clock. The hosts hold it (`Engine#turn_state`): the Worker reads it once
335
+ after it built the Engine and hands it to the Bridge and its own collaborators (`WorkerInbound`, `WorkerIdleExit`,
336
+ `ContinueOffer`), and the Engine hands it to its idle jobs (`IdleReminders`, `IdleRecap`). They call its readers,
337
+ `cancel!`, `record_activity` and the enqueued-id ledger; only the turn thread calls the writers (`begin!`,
338
+ `replace_context`, `ended!`, `finish!`). spec/bridge/turn_state_calls_spec.rb lists, per host file, the TurnState
339
+ methods it may call.
335
340
 
336
341
  - `begin!(context:, controller:, sink:, input_waiting:)`: all of it in one step, carried steers become steers. The
337
342
  context is built whole before (mode and git included), **so no reader sees a running turn with the last turn's
@@ -439,7 +444,7 @@ KernelLoop has its own `Turn` struct, a run's.
439
444
  TurnContext.**
440
445
  - Specs: `run_context(settings: …)` and `attach_services(kernel, tools: …)` (spec/support/test_kernel.rb).
441
446
  - `controller` is an in-process signal; another process stops a worker's turn through the Bridge (`POST cancel` →
442
- `Engine#cancel_current_turn!`).
447
+ `TurnState#cancel!`, on the Engine's TurnState the Worker handed the Bridge).
443
448
 
444
449
  **The live conversation and the checkpoint.** Both loops register the array they append to on the kernel
445
450
  (`KernelLoop#llm_context_turn`, `LLMContextForget::Turn#conversation`, tagged with the run's `turn_id`).
@@ -453,8 +458,9 @@ as a killed turn's (canceled, `worker_stopped`); the turn's end writes over it.
453
458
 
454
459
  ### SteerCut, GenerationPhase and WaitingSteer
455
460
 
456
- The Engine's one `SteerCut` (`steer_cut.rb`) owns a `GenerationPhase` and a `WaitingSteer`. The Bridge and the TUI
457
- ask it (`Engine#cut_for_steer`, `#input_epoch`, `#generation_snapshot`), the stream handler feeds it
461
+ The Engine's one `SteerCut` (`steer_cut.rb`) owns a `GenerationPhase` and a `WaitingSteer`. The Bridge holds it
462
+ (`Engine#steer_cut`, handed on by the Worker) and asks it (`#cut_for_steer`, `#input_epoch`, `#generation_snapshot`;
463
+ the Engine forwards the same three), the stream handler feeds it
458
464
  (`SteerCut#observe`), a drain that took input calls `#delivered!`, and `release_turn` calls `#finished!`.
459
465
 
460
466
  - `GenerationPhase`: whether a steer sent as a cut (`/cut TEXT`, `chi send --cut`) may cut the running generation.
@@ -465,6 +471,17 @@ ask it (`Engine#cut_for_steer`, `#input_epoch`, `#generation_snapshot`), the str
465
471
  - `WaitingSteer`: a cut that came too early. It waits until the thinking passes the cut wait (rechecked on each
466
472
  thinking chunk), until a drain hands it to the model at a boundary, or until the turn ends.
467
473
 
474
+ ### A block fix: written between turns
475
+
476
+ `Engine::BlockFixPart` (`engine/block_fix.rb`) is the one writer of the conversation outside a turn that a side
477
+ thread feeds. `#fix_block` (the Bridge's route) resolves the answer once, takes its anchor (index, digest, the turn
478
+ counter `#turn_messages` bumps for every turn) and asks on `SideJudgments#aside`; the result waits in
479
+ `@block_fix_ready` and wakes the worker. `#apply_block_fixes` runs only on the worker's loop between turns
480
+ (`Worker::BlockFixesPart`, after the queued commands and before the notes and the next prompt) and never while a turn
481
+ runs: under the event lock it replaces the session's messages (`replace_session_messages`) with a copy of the answer
482
+ whose text (no turn since, still the newest answer) or display (a turn since) holds the fix, or drops the fix when
483
+ the anchor no longer matches. See [block-renderers.md](block-renderers.md#a-failed-block-is-asked-for-again).
484
+
468
485
  ## Events
469
486
 
470
487
  ### The turn's sink (`on_event`) and the observers
@@ -475,11 +492,15 @@ observers (`Engine#subscribe`), which get a copy with a monotonic `event_seq`: t
475
492
  thinking tails, and in a worker the Bridge ([bridge.md](bridge.md)). **Errors in the sink or an observer are
476
493
  caught; they never break the turn.**
477
494
 
478
- `Engine#announce` puts an event that belongs to no turn (`Engine::ANNOUNCEABLE_EVENTS`: `turn_enqueued`,
495
+ `Engine#announce` puts an event that belongs to no turn (`SessionObserver::ANNOUNCEABLE_EVENTS`: `turn_enqueued`,
479
496
  `turn_dequeued` (`{enqueued_id, client_id}`: the remover's), `card`, `hook_notice`, `guardrail_warning`, `participants_changed`
480
497
  ([participants](participants.md#the-owners-terminal)), and more) to the observers only. `:side_usage` (a side
481
498
  request's usage and the session's side sums) goes to the observers the same way from `Engine#note_side_usage` (any
482
- thread), without being announceable.
499
+ thread), without being announceable. The list and the check are the event log's (`SessionObserver#announce`, the
500
+ same ArgumentError before anything is numbered); `Engine#announce` forwards to it. The Engine creates the log and
501
+ shows it (`Engine#event_log`): a worker's hosts (the Bridge, the Worker and its collaborators) hold that one log and
502
+ call it directly, so `Engine#subscribe`/`#unsubscribe`/`#event_count`/`#announce`/`#synchronize_events` stay for the
503
+ Engine's own parts, the one-shot host and Engine-only specs.
483
504
 
484
505
  Turn events (the main ones; `events.rb` keeps the shared sets):
485
506
 
@@ -772,7 +793,7 @@ are in [architecture.md](../architecture.md)'s file table.
772
793
  | `engine/participants.rb` | `Engine::ParticipantsPart`: the turn's author, a pair turn's stop, the participants line |
773
794
  | `engine/session.rb` | `Engine::SessionPart`: `#session=`, the state dir, the relay's view, the system prompt |
774
795
  | `engine/verify.rb` | `Engine::VerifyPart`: the Verify/Revise anchors' stage builder |
775
- | `engine/questions.rb` | `Engine::QuestionsPart`: ask-user-question (QuestionDesk, forwarded) |
796
+ | `engine/questions.rb` | `Engine::QuestionsPart`: ask-user-question (QuestionDesk, forwarded: the hosts hold `Engine#question_desk`; the forwards stay for the Engine's parts, the one-shot and Engine-only specs) |
776
797
  | `engine/toolkit.rb` | `Engine::ToolkitPart`: the toolkit, `ctx.load_tools`, the toolkit suggestion's builder |
777
798
  | `engine/context_judge.rb` | `Engine::ContextJudgePart`: the candidate judge's builder and `judge_late_candidates` |
778
799
  | `engine/turn_helpers.rb` | `Engine::TurnHelpersPart`: turn settings, images, model ref, used memories, the warm-up's builder |
@@ -113,7 +113,9 @@ session switch, a turn's end, Revise's clones, the stage's hand-off to `#history
113
113
  listeners. A widget's position and picks live in the widget, so a clone or a rewrite starts over (accepted for v1).
114
114
  - **A refused block** (`data-widget-error`) stays source under `failBlock`'s muted `.block-note` ("Couldn't draw this
115
115
  chi-ui block: …", an attribute CSS shows, a click copies it). Bad JSON or an unknown `type` fails the same way, from
116
- the watcher. A `chi-ui` `<pre>` with neither attribute (an older server) is left alone.
116
+ the watcher. A `chi-ui` `<pre>` with neither attribute (an older server) is left alone. In the newest answer a
117
+ refused block is asked for again, once (the schemas go with the request: `InlineWidgets::FIX_RULES`, and the fix
118
+ must parse before it is used; [block-renderers.md](block-renderers.md#a-failed-block-is-asked-for-again)).
117
119
  - **walk** (`widget_walk.js`): the swimlane (one column per actor, one row per step; the current, seen and a hovered
118
120
  case's target marked; a click jumps), the step card (actor, `does`, "You see", the dashed "Behind it"), a fork's
119
121
  "Which case?" buttons, Back / Next / Start over, the path taken, and ← → while the widget has the focus
@@ -192,7 +192,15 @@ user message starts (`KernelLoop#warmup_prompt`) and sends it in a thread (`Clie
192
192
  server has since cleared skips its prompt cache and prefills everything (measured 0.5 s → 12 s). For the same
193
193
  reason `id_slot` is a reserved sampling key.
194
194
  - What breaks it (the warm-up simply misses): a system-prompt rebuild (`/thinking`, `/model`, a tool change),
195
- the image cut moving a batch, `!rollback`.
195
+ the image cut moving a batch, `!rollback`, a block fix that patched the last answer.
196
+
197
+ **A block fix patches the last answer before a turn sends it.** A block the page couldn't draw in the newest answer
198
+ is asked for again on the side, and when it comes back before the next turn starts the answer's text holds the fix
199
+ ([block-renderers.md](block-renderers.md#a-failed-block-is-asked-for-again)): that is the one change to an earlier
200
+ message a turn's request sees. The cached prefix ends before the answer on a remote prefix cache and on Anthropic's
201
+ Messages API (nothing lost); on llama.cpp the slot re-evaluates from the patched block (a few hundred tokens), and a
202
+ warm-up already sent loses its gain for that turn (measured 0.73 s against 0.11 s on a hybrid model). A fix that comes
203
+ back after the next turn started lands in the answer's `display` only, never sent to a model.
196
204
 
197
205
  ## The image window
198
206