samagotchi 0.162.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 66e023d71f974fccd3b2767f7a45d876663217d787f4c38b177e7074732fdf6b
4
- data.tar.gz: 32dd57df62fa6b818b2b801b678ad253ae93d1adf5a0821c4eed0ce61b39830a
3
+ metadata.gz: 3d57e659db748e1c159bf12ee6bea47b2d0f15b23385ceeb52f7e97b74e15f10
4
+ data.tar.gz: 68c4953fa92ad429a13b88ca27c88cd11cb4824199fbcbd5a41000e962618617
5
5
  SHA512:
6
- metadata.gz: c6cec4ce646d2759235f417e6bea5cb818c4dac96f1395c9a2fd79476ca1ca6428921f02ef61345339cb8b4c7fe51d17fd4d3a5affbc1e4a30dd2448680c597c
7
- data.tar.gz: 1d2b52160476da47449b1e72112a97cbbfd0888fdaa7203834776afaf914b149c8b11b3915b566f0e9542c996c074a81c09959ad37ce2ce08a8943924b51327f
6
+ metadata.gz: 05d62b9520edc30b4171a2a04efb337750d28ad12ea3e596d14a010604f06a4e2762a7e29b223fcefefbe9bf27247984affa5734c83792adf140c4ff34a598ae
7
+ data.tar.gz: 458cacd81cf57afcd8efd6be0115220bba4b5fd1183f3de39b23a5b5671740a0cadc17971f66994aa92a6e9ff1c1a4abfdb221fa746c4e38d6beb2a34c6a7a44
data/CHANGELOG.md CHANGED
@@ -8,6 +8,21 @@ 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
+
11
26
  ## [0.162.0] - 2026-11-10
12
27
 
13
28
  ### Changed
@@ -6029,7 +6044,8 @@ and long-lived sessions.
6029
6044
  - A macOS desktop helper (`chi desktop install`): a "Send to chi" Service and a
6030
6045
  hotkey panel that send selected text or the clipboard to your sessions.
6031
6046
 
6032
- [Unreleased]: https://github.com/dm1try/samagotchi/compare/v0.162.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
6033
6049
  [0.162.0]: https://github.com/dm1try/samagotchi/compare/v0.161.0...v0.162.0
6034
6050
  [0.161.0]: https://github.com/dm1try/samagotchi/compare/v0.160.0...v0.161.0
6035
6051
  [0.160.0]: https://github.com/dm1try/samagotchi/compare/v0.159.0...v0.160.0
data/docs/architecture.md CHANGED
@@ -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). |
@@ -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
@@ -88,9 +90,13 @@ accumulator's final fold of the turn (its parts in order, in-turn cards included
88
90
  cached by the file's path, size and mtime. `#last` is the newest line this worker wrote or started from.
89
91
  `TurnDrawings.cover(lines, messages, timing:, entries:, skip_turn_id:, session_id:, cwd:)` is what a show draws
90
92
  finished turns from (pure): `valid`'s lines, and for each `TurnRanges` range none overlaps (the running turn's
91
- left out), a line `Synth.memoized` makes from its messages, the timing's records and CardStore's entries. A made
92
- range whose id a kept line has (a failed turn's kept steps, then its re-run under that id) is renamed `<id>~<from>`,
93
- so no two lines share an id. `TurnRanges.of(messages)` (`bridge/turn_ranges.rb`) reads a session's turns
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
94
100
  back from its messages as the Engine cuts them (`kept_from…kept_to`: the reminders before an opening start a turn; a
95
101
  note after it, a `!cmd`'s record and a wake's note stay outside), with a display id for a turn with none
96
102
  (`m<from>-<digest8>`) or a repeated one (`<id>~<from>`); `TurnRanges.records` pairs each with its turn record by id,
@@ -126,22 +132,29 @@ accumulator's final fold of the turn (its parts in order, in-turn cards included
126
132
  rebuilds rows from the messages any more. `chi --remote` attaches through chi web's stream proxy,
127
133
  which relays an owner's frames byte for byte, the field included. A participant never gets it: its stream's snapshot
128
134
  is bare (`ParticipantView`). An older TUI ignores the field; an older worker sends none.
129
- - **The show.** chi web's full read with `?parts=1&drawings=1` (the page's) draws every finished turn from a line:
130
- `SessionShow#drawn_lines` is `TurnDrawings.cover` over the file, the show's timing records and its cards (CardStore's
131
- list, live or saved), the running turn (`current_turn`'s id) left out. A file that can't be read gives no lines, so
132
- every turn is made from its messages; should the cover itself fail (`turn_drawings_uncovered`), the turns draw as
133
- before. It stamps each display item of a kind a
134
- drawing draws (the opening, steps, steers, merged lines, the empty answer) in a line's range with `drawn: <turn_id>`
135
- 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 =>
136
144
  {events, end}}`: `TurnAccumulator.replay_events(drawing, cards: true)`, the one unfold, in Ruby. A context note in
137
- a range and a `!cmd`'s record are not stamped. Without `drawings=1` (an older page) the read is what it was.
138
- 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
139
- drawing (`cards_place.js`). A live worker whose sidecar features lack `turn_drawings` (`TurnDrawings::FEATURE`:
140
- an older one lists no `of_turn`) gets no drawings in the show: its turns all draw as before. The stamps walk the
141
- lines with one cursor and the unfold reads a Set of stamped ids, so a long session's show is linear in its turns;
142
- a made-up line is memoized per range (`Synth.memoized`), so a show after a turn end makes no old turn again.
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).
143
152
  - **Compat.** An older worker writes nothing, a continue (a note, no turns) and a review fork copy no drawings, and
144
- an older chi's fork or one-shot wrote none: their turns are made from their messages. The lines a fork carries and a
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
145
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
146
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
147
160
  reads as any drawn turn's (an older page ignores `record_id` and finds no record for such a turn: no timing line;
@@ -440,7 +453,7 @@ The Bridge exposes:
440
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).
441
454
  - `GET /session/:id/snapshot` — the snapshot frame's content as one request (the web server renders
442
455
  the messages itself, then streams from its `event_seq`). Read by the web's full show
443
- (`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.
444
457
  - `GET /session/:id/tail` — the page's light re-read (`Bridge#tail_frame`): `session_state_snapshot`,
445
458
  `working_directory` (the session's folder, which the web checks the answer's file refs against),
446
459
  `answer` (the last message a UI shows as an answer, `AnswerTail`: the one message, copied alone),
@@ -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. 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). An item that comes unstamped (an older chi web, a miss) is still rebuilt from its messages | 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/testing.md CHANGED
@@ -182,11 +182,17 @@ Each level owns its own share; a detail is asserted once, at the lowest level th
182
182
  rewrites their lines and show after an intended change) feed `turn_drawing_parity.test.js`, which draws each one
183
183
  live (the real stream handlers and stage) and from its drawing and compares the shapes with no allow list.
184
184
  `spec/shared/turn_ranges.json` (`UPDATE_TURN_RANGES=1 bundle exec rspec spec/bridge/turn_ranges_spec.rb`) pins
185
- `Bridge::TurnRanges`' turns and record pairing against `timing.js turnGroups` (timing.test.js). Each scenario's
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
186
187
  fixture also holds `synth`, the show drawn from `TurnDrawings::Synth`'s lines (written by
187
188
  `spec/bridge/turn_drawings_synth_spec.rb`, which also compares each synth line with the live one minus
188
189
  `Synth::LOSSES`); the parity test's synth arm draws it against live, each scenario naming the losses that change its
189
- shape (`SYNTH_LOSSES_OF`). The
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
190
196
  `lan` project's chi web is on the LAN only
191
197
  when the machine has a private IPv4: without one its LAN tests skip and the participant review journey runs on
192
198
  loopback.
@@ -56,12 +56,16 @@ module Samagotchi
56
56
  tool_action: "a plugin tool's own action words (its label when saved, else 'calling tool')",
57
57
  wake_start: "a wake turn's start time when no message of its own is stamped: its note's, written before it began",
58
58
  failure_detail: "a failed turn's error message and class when its record keeps a summary (SessionMetrics#failure_fields)",
59
- repeated_turn_id: "a range whose turn id an earlier one has (…~N): no record, no CardStore entries (whose they are " \
60
- "can't be told)",
59
+ repeated_turn_id: "a range whose turn id an earlier one has (…~N), or a made range renamed because a kept line " \
60
+ "has its id (a failed turn's kept steps, then its re-run): no record (no timing line), no " \
61
+ "CardStore entries (the runs' records share the id: whose they are can't be told)",
61
62
  continued_steps: "a Continue's steps right after its turn read as that turn's (no message tells them apart): " \
62
63
  "the turn's record and kind, the Continue's calls untimed, its own CardStore entries left out",
63
64
  unopened_turn: "a turn with no opening (a reminder's, a Continue's) has no id in the messages: a made-up one, " \
64
- "and no record to pair by"
65
+ "and no record to pair by",
66
+ fork_before_first_turn: "a /btw keep child saved without its system head: the lines it carried keep the " \
67
+ "parent's indices and hold only once its first turn puts the head back; until " \
68
+ "then its turns are made, without CardStore rows (the child's store is empty)"
65
69
  }.freeze
66
70
 
67
71
  # A Synth line that couldn't be made (its minimal line stands in).
@@ -243,17 +243,23 @@ module Samagotchi
243
243
  messages = Array(messages)
244
244
  real = Degrade.call(:web, "turn_drawings_unreadable", fallback: []) { valid(lines, messages) }
245
245
  ranges = TurnRanges.of(messages)
246
- open = uncovered(ranges, real)
247
- ranges = reserve_ids(ranges, open, real)
248
- turn_records = list_of(timing, :turn_records)
249
- records = TurnRanges.records(ranges, turn_records)
246
+ records = TurnRanges.records(ranges, list_of(timing, :turn_records))
247
+ taken = real.to_set(&:turn_id)
250
248
  tools = list_of(timing, :tool_records).group_by { |t| field(t, :turn_id) }
251
249
  own = Array(entries).select { |e| e.is_a?(Hash) && field(e, :of_turn) }.group_by { |e| field(e, :of_turn) }
252
- made = open.filter_map do |i|
253
- range = ranges[i]
254
- next if skip_turn_id && range.turn_id == skip_turn_id
255
-
256
- record = records[i]
250
+ made = uncovered(ranges, real).filter_map do |i, part|
251
+ next if skip_turn_id && ranges[i].turn_id == skip_turn_id
252
+
253
+ # A made range whose id a kept line has (a failed turn's kept
254
+ # steps, then its re-run under the same turn id: .valid keeps the
255
+ # newest line for an id) is renamed "<id>~<from>": never two
256
+ # lines with one id (the page would draw them as one turn), and
257
+ # not its turn's own (no end turn_id, no record).
258
+ range = taken.include?(part.id) ? part.with(id: "#{part.id}~#{part.from}") : part
259
+ # A piece with its turn's opening is that turn's (by its own id,
260
+ # else by place for a turn saved before turn ids); one without
261
+ # (a Continue's steps after a lined turn) has no record.
262
+ record = records[i] if range.opening && (range.turn_id.nil? || range.own_id?)
257
263
  # The turn's tool records by its record's id, else its own (a
258
264
  # record lost, its tool records saved: the TUI's join does so too).
259
265
  tool_id = record ? field(record, :id) : (range.turn_id if range.own_id?)
@@ -263,34 +269,43 @@ module Samagotchi
263
269
  (real + made).sort_by(&:from)
264
270
  end
265
271
 
266
- # +ranges+ with each one to be made (+open+, indexes) whose id a kept
267
- # line has (a failed turn's kept steps, then its re-run under the same
268
- # turn id: .valid keeps the newest line for an id) renamed "<id>~<from>":
269
- # never two lines with one id (the page would draw them as one turn),
270
- # and not its turn's own (no end turn_id, record or entries).
271
- def reserve_ids(ranges, open, lines)
272
- taken = lines.to_set(&:turn_id)
273
- return ranges if taken.empty?
274
-
275
- made = open.to_set
276
- ranges.each_with_index.map do |range, i|
277
- made.include?(i) && taken.include?(range.id) ? range.with(id: "#{range.id}~#{range.from}") : range
278
- end
279
- end
280
- private :reserve_ids
281
-
282
- # The indexes of +ranges+ no line of +lines+ (sorted by from, apart)
283
- # overlaps: one walk over both.
272
+ # The parts of +ranges+ no line of +lines+ (sorted by from, apart)
273
+ # overlaps, as [range index, range]: a range none overlaps whole,
274
+ # and a range one covers in part (a Continue's steps read as the
275
+ # turn before's, TurnRanges, with only one of the two lined) split
276
+ # at the lines' bounds, so no turn item is left without a line. One
277
+ # walk over both.
284
278
  def uncovered(ranges, lines)
285
279
  at = 0
286
- ranges.each_index.reject do |i|
287
- range = ranges[i]
280
+ ranges.each_with_index.flat_map do |range, i|
288
281
  at += 1 while at < lines.size && lines[at].to >= 0 && lines[at].to <= range.from
289
- at < lines.size && lines[at].from < range.to
282
+ from = range.from
283
+ gaps = []
284
+ (at...lines.size).each do |k|
285
+ break unless lines[k].from < range.to
286
+
287
+ gaps << [from, lines[k].from] if lines[k].from > from
288
+ from = [from, lines[k].to].max
289
+ end
290
+ gaps << [from, range.to] if from < range.to
291
+ gaps.map { |a, b| [i, piece(range, a, b)] }
290
292
  end
291
293
  end
292
294
  private :uncovered
293
295
 
296
+ # +range+'s messages [+from+, +to+): the range itself when whole; a
297
+ # part with its opening keeps its id; one without is made up
298
+ # ("<id>~<from>", no turn id: no record, no CardStore entries).
299
+ def piece(range, from, to)
300
+ return range if from == range.from && to == range.to
301
+
302
+ opening = range.opening && (range.opening < range.from ? from == range.from : (from...to).cover?(range.opening))
303
+ return range.with(from: from, to: to) if opening
304
+
305
+ TurnRanges::Range.new(from: from, to: to, id: "#{range.id}~#{from}", turn_id: nil, opening: nil)
306
+ end
307
+ private :piece
308
+
294
309
  # A fork's drawings (Plugin::Sessions#fork, before its child's worker
295
310
  # spawns: no other writer): the lines of +from_dir+'s file that hold
296
311
  # against the child's seed +messages+ (same indices, same ends; a range
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: samagotchi-system
3
- version: 0.162.0
3
+ version: 0.163.0
4
4
  scope: system
5
5
  description: Default system memories — identity, self map, config modification protocol, memory guide and the delegated-session rules
6
6
  files:
@@ -7,6 +7,7 @@ require_relative "guardrails/path_resolve"
7
7
  require_relative "memory_paths"
8
8
  require_relative "paths"
9
9
  require_relative "project_init"
10
+ require_relative "project_subfolders"
10
11
 
11
12
  module Samagotchi
12
13
  # `chi project`: which project this folder is in (MemoryPaths.lookup: a
@@ -19,7 +20,7 @@ module Samagotchi
19
20
  include CLI::Command
20
21
 
21
22
  USAGE = <<~TEXT
22
- Usage: chi project [init [--new-id] [DIR]]
23
+ Usage: chi project [init [--new-id | --merge-subfolders] [DIR]]
23
24
  (none) this folder's project: how it was found (git, marker or none), its root, its
24
25
  top, its id and its project memories folder
25
26
  init [DIR] make DIR (default: this folder; created when missing) a chi project: writes
@@ -29,12 +30,20 @@ module Samagotchi
29
30
  marked folder with no id: adopts one, moving its folders to it
30
31
  --new-id a marked folder's own new id (a copied folder going its own way): its
31
32
  memories and project context copied to it
33
+ --merge-subfolders
34
+ move the memories sessions saved in DIR's subfolders before init (each
35
+ keyed by its subfolder's path) into the project's; one the project has by
36
+ that name stays and is named. Marks DIR first when it isn't yet. Not while
37
+ a session in DIR runs
32
38
  TEXT
33
39
 
34
40
  SUBCOMMANDS = %w[init].freeze
35
41
  FLAGS = {
36
42
  nil => CLI::Flags.new(help: HELP_WORDS, args: false),
37
- "init" => CLI::Flags.new(help: HELP_WORDS) { |f| f.switch "--new-id" }
43
+ "init" => CLI::Flags.new(help: HELP_WORDS) do |f|
44
+ f.switch "--new-id"
45
+ f.switch "--merge-subfolders"
46
+ end
38
47
  }.freeze
39
48
 
40
49
  # @param cwd [String] the folder asked about (Dir.pwd)
@@ -68,8 +77,15 @@ module Samagotchi
68
77
  return run_show unless @sub
69
78
  return usage_error("init takes one folder") if parsed.args.size > 1
70
79
 
80
+ if parsed.options[:new_id] && parsed.options[:merge_subfolders]
81
+ return usage_error("--merge-subfolders and --new-id don't go together")
82
+ end
83
+
71
84
  dir = File.expand_path(parsed.args.first || @cwd, @cwd)
72
- parsed.options[:new_id] ? run_new_id(dir) : run_init(dir)
85
+ return run_new_id(dir) if parsed.options[:new_id]
86
+ return run_merge(dir) if parsed.options[:merge_subfolders]
87
+
88
+ run_init(dir)
73
89
  end
74
90
 
75
91
  private
@@ -89,6 +105,8 @@ module Samagotchi
89
105
  row("id", found.id) if found.id
90
106
  row("memories", memories_line(found))
91
107
  notes(found).each { |note| row("note", note) }
108
+ subfolders_note = found.marker? && subfolders_message(found.root)
109
+ row("note", subfolders_note) if subfolders_note
92
110
  CLI::Exit::OK
93
111
  end
94
112
 
@@ -124,7 +142,9 @@ module Samagotchi
124
142
  !@home.to_s.empty? && Guardrails::PathResolve.real(found.top) == Guardrails::PathResolve.real(@home)
125
143
  end
126
144
 
127
- def run_init(dir)
145
+ # @param merging [Boolean] --merge-subfolders follows: no subfolders line
146
+ def run_init(dir, merging: false)
147
+ @merging = merging
128
148
  outcome = ProjectInit.adopt(dir, home: @home, env: @env, state_dir: @state_dir, sessions: adopt_rows(dir))
129
149
  case outcome.kind
130
150
  when :git
@@ -137,12 +157,14 @@ module Samagotchi
137
157
  CLI::Exit::FAILED
138
158
  when :already_marked
139
159
  @stdout.puts(outcome.message)
160
+ subfolders_line(outcome.root)
140
161
  CLI::Exit::OK
141
162
  when :created
142
163
  report_init(outcome)
143
164
  CLI::Exit::OK
144
165
  when :adopted
145
166
  @stdout.puts(outcome.message)
167
+ subfolders_line(outcome.root)
146
168
  CLI::Exit::OK
147
169
  end
148
170
  rescue SystemCallError => e
@@ -162,13 +184,58 @@ module Samagotchi
162
184
  CLI::Exit::OK
163
185
  end
164
186
 
187
+ # `chi project init --merge-subfolders`: refused while a session in
188
+ # DIR (or a subfolder: a pre-init one stored its own cwd) runs, checked
189
+ # before anything is written; then init as usual (marks or adopts an
190
+ # id), then ProjectSubfolders.merge into the project's memories folder.
191
+ def run_merge(dir)
192
+ root = Guardrails::PathResolve.real(dir)
193
+ running = ProjectSubfolders.running(root, sessions: session_rows, home: @home)
194
+ unless running.empty?
195
+ error_line("#{command_name}: #{ProjectSubfolders.running_message(root, running)}")
196
+ return CLI::Exit::FAILED
197
+ end
198
+
199
+ code = run_init(dir, merging: true)
200
+ return code unless code == CLI::Exit::OK
201
+
202
+ found = lookup(dir)
203
+ return CLI::Exit::OK unless found.marker? && found.id
204
+
205
+ target = File.join(MemoryPaths.projects_dir(env: @env), found.id)
206
+ subfolders = ProjectSubfolders.find(found.root, sessions: session_rows, env: @env, home: @home)
207
+ ProjectSubfolders.merge(subfolders, target: target, env: @env).each { |line| @stdout.puts(line) }
208
+ CLI::Exit::OK
209
+ rescue SystemCallError => e
210
+ error_line("#{command_name}: couldn't move the subfolders' memories: #{e.message}")
211
+ CLI::Exit::FAILED
212
+ end
213
+
214
+ # This machine's sessions, listed once per run (a walk of every session file).
215
+ def session_rows = @session_rows ||= @sessions.call
216
+
217
+ # ProjectSubfolders' text for +root+, or nil (none, or no listing).
218
+ def subfolders_message(root)
219
+ ProjectSubfolders.message(ProjectSubfolders.find(root, sessions: session_rows, env: @env, home: @home))
220
+ rescue StandardError => e
221
+ error_line("#{command_name}: couldn't list this machine's sessions (#{e.message})")
222
+ nil
223
+ end
224
+
225
+ def subfolders_line(root)
226
+ return if @merging
227
+
228
+ text = subfolders_message(root)
229
+ @stdout.puts(text) if text
230
+ end
231
+
165
232
  # The rows an adoption checks for running sessions: only for a marked
166
233
  # folder (a listing is a walk of every session file).
167
234
  def adopt_rows(dir)
168
235
  found = lookup(dir)
169
236
  return [] if found.git? || found.id
170
237
 
171
- @sessions.call
238
+ session_rows
172
239
  end
173
240
 
174
241
  def report_init(outcome)
@@ -178,6 +245,7 @@ module Samagotchi
178
245
  row("id", outcome.id) if outcome.id
179
246
  row("memories", memories_line(lookup(root)))
180
247
  @stdout.puts(outcome.message) if outcome.message
248
+ subfolders_line(root)
181
249
  sessions_note(root)
182
250
  end
183
251
 
@@ -187,7 +255,7 @@ module Samagotchi
187
255
  # restarts; a running chi web groups the older ones after its restart
188
256
  # (SessionHub looked their project up once).
189
257
  def sessions_note(root, restart: nil)
190
- rows = @sessions.call.select { |r| !r.cwd.to_s.empty? && lookup(r.cwd.to_s).root == root }
258
+ rows = session_rows.select { |r| !r.cwd.to_s.empty? && lookup(r.cwd.to_s).root == root }
191
259
  return if rows.empty?
192
260
 
193
261
  live = rows.select(&:live)