samagotchi 0.176.0 → 0.177.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +47 -1
- data/docs/architecture.md +5 -4
- data/docs/cli.md +12 -5
- data/docs/internals/bundles.md +4 -3
- data/docs/internals/participants.md +10 -6
- data/docs/internals/prompt-caching.md +3 -0
- data/docs/internals/session-lifecycle.md +167 -0
- data/docs/internals/web-frontend.md +25 -8
- data/docs/internals/working-set.md +78 -6
- data/docs/plugins.md +1 -1
- data/docs/releasing.md +3 -2
- data/docs/sessions.md +8 -5
- data/docs/testing.md +4 -2
- data/lib/samagotchi/bridge.rb +3 -3
- data/lib/samagotchi/bundle_command/check.rb +1 -1
- data/lib/samagotchi/bundles/system/manifest.yml +1 -1
- data/lib/samagotchi/compat.rb +1 -1
- data/lib/samagotchi/engine/models.rb +11 -0
- data/lib/samagotchi/engine/session.rb +16 -0
- data/lib/samagotchi/engine.rb +1 -0
- data/lib/samagotchi/engine_snapshots.rb +3 -0
- data/lib/samagotchi/memory_bundle/shipped_update.rb +1 -1
- data/lib/samagotchi/note_delivery.rb +9 -4
- data/lib/samagotchi/plugin/sessions.rb +2 -1
- data/lib/samagotchi/prompt_part.rb +66 -0
- data/lib/samagotchi/revise_anchor.rb +2 -0
- data/lib/samagotchi/schedules.rb +3 -1
- data/lib/samagotchi/session.rb +10 -1
- data/lib/samagotchi/session_chain/delete.rb +28 -5
- data/lib/samagotchi/session_chain/delete_preview.rb +2 -2
- data/lib/samagotchi/session_inbox.rb +29 -0
- data/lib/samagotchi/session_inbox_delivery.rb +13 -5
- data/lib/samagotchi/session_lifecycle/allowed.rb +66 -0
- data/lib/samagotchi/session_lifecycle/canonical.rb +49 -0
- data/lib/samagotchi/session_lifecycle/reading.rb +65 -0
- data/lib/samagotchi/session_lifecycle.rb +59 -0
- data/lib/samagotchi/session_manager/delivery.rb +29 -6
- data/lib/samagotchi/session_manager/lifecycle.rb +22 -14
- data/lib/samagotchi/session_manager/removal.rb +16 -8
- data/lib/samagotchi/session_manager/spawn.rb +2 -2
- data/lib/samagotchi/sessions_command.rb +1 -1
- data/lib/samagotchi/system_prompt.rb +211 -12
- data/lib/samagotchi/tool_names.rb +1 -1
- data/lib/samagotchi/tools/memory.rb +29 -0
- data/lib/samagotchi/turn_anchors.rb +5 -0
- data/lib/samagotchi/verify_anchor.rb +2 -0
- data/lib/samagotchi/version.rb +1 -1
- data/lib/samagotchi/web/participant_show.rb +4 -5
- data/lib/samagotchi/web/participant_view.rb +4 -6
- data/lib/samagotchi/web/public/app.js +3 -0
- data/lib/samagotchi/web/public/ctx_tokens.js +33 -0
- data/lib/samagotchi/web/public/data.js +6 -2
- data/lib/samagotchi/web/public/delete_sheet.js +42 -5
- data/lib/samagotchi/web/public/index.html +43 -9
- data/lib/samagotchi/web/public/session_fields.js +10 -4
- data/lib/samagotchi/web/public/session_prefs.js +5 -2
- data/lib/samagotchi/web/public/session_state.js +14 -1
- data/lib/samagotchi/web/public/session_store.js +1 -1
- data/lib/samagotchi/web/public/session_view.js +1 -1
- data/lib/samagotchi/web/public/stream_handlers.js +7 -3
- data/lib/samagotchi/web/public/tokens.css +2 -2
- data/lib/samagotchi/web/public/working_set.js +51 -7
- data/lib/samagotchi/web/public/working_set_view.js +188 -58
- data/lib/samagotchi/web/public/ws_sections.js +252 -0
- data/lib/samagotchi/web/session_control.rb +4 -3
- data/lib/samagotchi/web/session_show.rb +13 -2
- data/lib/samagotchi/web/session_summary.rb +7 -0
- data/lib/samagotchi/worker/command_queue.rb +5 -1
- data/lib/samagotchi/worker/startup.rb +1 -1
- data/lib/samagotchi/worker.rb +1 -0
- data/lib/samagotchi/worker_boot.rb +9 -6
- data/lib/samagotchi/worker_presence.rb +4 -0
- data/lib/samagotchi/working_set.rb +32 -4
- data/lib/samagotchi/working_set_command.rb +3 -2
- data/lib/samagotchi/working_set_steer.rb +14 -3
- metadata +9 -1
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
# The working set: what the model really has
|
|
2
2
|
|
|
3
3
|
The stage view's working set (`web.working_set`, [cli.md](../cli.md#the-working-set)) shows the files, memories
|
|
4
|
-
and URLs a session's tool runs brought into the model's context
|
|
4
|
+
and URLs a session's tool runs brought into the model's context, and model notes carried in the system prompt as
|
|
5
|
+
`prompt` rows. The page builds the set itself from its tool rows
|
|
5
6
|
(`working_set.js`, phase 1). The server says what the model still has of each item: **live**, **stale** (a file
|
|
6
7
|
changed since the model last saw it) or **forgotten** (nothing of it is still sent), and its size in tokens. This
|
|
7
8
|
page covers the server's side and how the page overlays it.
|
|
@@ -49,8 +50,13 @@ is pure and returns a `WorkingSet::Snapshot` (`items`, `at`: the conversation's
|
|
|
49
50
|
key). Each `WorkingSet::Item` is `kind` (`file`, `memory`, `url`), `key`, `state` (`live`, `stale`, `forgotten`,
|
|
50
51
|
`dropped`), `tokens`, `ops`, `count`,
|
|
51
52
|
`first_id` (the first run's ToolIds id), `pinned` (the session's `working_set_pins` name it, whatever the
|
|
52
|
-
strategy: the page shows the mark only under forget, so a switch shows it at once)
|
|
53
|
-
outputs holds the user's applied drop, whatever the state: an undrop has something to take back)
|
|
53
|
+
strategy: the page shows the mark only under forget, so a switch shows it at once), `has_drop` (any of its content
|
|
54
|
+
outputs holds the user's applied drop, whatever the state: an undrop has something to take back) and, for a memory,
|
|
55
|
+
`scope`: the scope its latest `memory_read` answered from (the memory stamp's file, as `MemoryPart#scope` reads it;
|
|
56
|
+
`memory_item_scope`, no text read), in `to_h` only when known (nil for a memory only written, or read before memory
|
|
57
|
+
stamps). Cost: one field per memory item, from the stamp lookup the stale check makes anyway. Known limit: the set
|
|
58
|
+
has one item per memory name, so a session that read both a project `x` and a system `x` has one item carrying the
|
|
59
|
+
latest read's scope. The Engine's event and the GET
|
|
54
60
|
both pass the session's pins.
|
|
55
61
|
|
|
56
62
|
**Runs.** It pairs the runs twice with `LLMContextStale.paired_runs`: once on the stored conversation, once on what
|
|
@@ -220,9 +226,12 @@ projection), on both loops. It costs one model step; a model may skip it (the no
|
|
|
220
226
|
- **`WorkingSetSteer.add`** refuses an item already added (pending), a URL not http(s) (`web_fetch` fetches only
|
|
221
227
|
those), what the caller's `found` look says can't be read (`WorkingSetCommand#missing`: a file not there or a
|
|
222
228
|
directory; a memory name `memory_read` rejects or that neither scope holds), an item holding the user's drop
|
|
223
|
-
(`undrop_first`: undrop brings it back without a step),
|
|
224
|
-
|
|
225
|
-
|
|
229
|
+
(`undrop_first`: undrop brings it back without a step), one already in the system prompt and with no working-set
|
|
230
|
+
output (`in_prompt`: nothing to add; matched by name and scope, `Tools::MemoryRead.prompt_memory?` over
|
|
231
|
+
`Engine#prompt_memories`, a bare name or an unscoped prompt entry by name only), and one the model has whole (`already_sent`: live, a read of it sent). The
|
|
232
|
+
prompt-only refusal doesn't apply when the set holds a read of that memory: a stale or forgotten item may still be
|
|
233
|
+
added as the web row's `refresh`. **`unadd`** takes a pending add back (free); without one it is refused
|
|
234
|
+
(`not_added`).
|
|
226
235
|
- **The note**: an add always joins it (`the user added lib/tax.rb, memory style to your context: before anything
|
|
227
236
|
else, load them with read "/abs/lib/tax.rb", memory_read "style"`); a file is named by its absolute path in the
|
|
228
237
|
call, since a `read` resolves a relative path against the process's folder. An unadd cancels its add there.
|
|
@@ -316,6 +325,69 @@ passes `working_set_updated` to it, and does nothing when the flag is off. A new
|
|
|
316
325
|
`details_motion.js` skips `.ws-foot`, and `footClick` cancels the click;
|
|
317
326
|
- the rail (`onServer`, the stage's `scheduleRefresh`).
|
|
318
327
|
|
|
328
|
+
**The list's lens.** The expanded list is always the session's set (`sessionSet()`), seen through a lens: `null`
|
|
329
|
+
(the session) or a turn's index (`createWorkingSet`'s `lens`). The chip (and the reader's `‹ Set`, `openList`) opens the
|
|
330
|
+
session lens; a footprint (`footClick`) and the rail (`openTurn`) open the lens on their turn. In a turn lens
|
|
331
|
+
(`working_set.js turnLens`, `lensItem`) the rows the turn touched are `lit` and the rest `dim` (`opacity:
|
|
332
|
+
var(--ws-lens-dim)`, a `:root` token in both palettes). A lit row is the session item's state, tokens and actions with
|
|
333
|
+
the turn item's `at`, ops and count (its step tag is the turn's, `s3`; a dimmed row keeps the session's, `t1·s3`): the
|
|
334
|
+
turn item is passed through, the session item is never overwritten. The header's `session | ‹ turn N ›` steps over the
|
|
335
|
+
finished turns and the running one (`lastTurn()`), `‹` and `›` disabled at the ends; the line under it reads "turn N
|
|
336
|
+
touched A · B new" (new: the session set's first `at` is this turn's, a prompt memory never). A folded inner group
|
|
337
|
+
(`labelsTemplate`) shows its lit members while folded. A new seed that leaves the lens past the last turn, or a reset
|
|
338
|
+
that drops the running turn, puts it back to the session.
|
|
339
|
+
|
|
340
|
+
**The head view: sections** (`ws_sections.js headSections`, drawn by `working_set_view.js headTemplate`). With the
|
|
341
|
+
session's `prompt_parts` (the worker's sizes of its system prompt; `promptParts` on the page) the list is what is in
|
|
342
|
+
chi's head, in three sections:
|
|
343
|
+
- **From the start** (`start`): every part in prompt order, the tools part first. A memory part (identity, a model
|
|
344
|
+
note, a preload) IS a memory row: merged with the session set's rows of the same memory, else a row of its own
|
|
345
|
+
(identity: the set never lists it). **The match is scope + name** (`same`): the names match (`memoryName`, which
|
|
346
|
+
also reads an older page's preloaded `system/x` as `x`) and so do the scopes (the part's `scope`, the item's from the
|
|
347
|
+
server, `overlay`); a scope either side lacks (an older worker's part or item, an item the server hasn't stamped)
|
|
348
|
+
matches by name alone, as before scopes. So a project `x` read beside a system `x` in the prompt is two rows: the
|
|
349
|
+
read stays in Read as a plain read (not "prompt", never held twice), and the part's own row gets the key `x@system`
|
|
350
|
+
(no collision with the read's `x`), its words its scope ("preloaded · system") and, like identity's, no actions or
|
|
351
|
+
peek. A note and a preload of one name and scope stay one row with both sizes; of two scopes, two rows. The start
|
|
352
|
+
section tracks the items it shows by identity, not by key. It keeps the memory row's peek, state and the drop/pin rules of a preloaded memory (not
|
|
353
|
+
droppable or pinnable until read). Its tokens are the part's, plus `+X` for the read's (the item's server tokens: a
|
|
354
|
+
preloaded row carries none of its own, so the two never double-count). Other parts are read-only `part` rows: a
|
|
355
|
+
label, a sub (the tools part's "N declared"; dropped on a phone), `~tokens`, no actions, no peek; a turn lens dims
|
|
356
|
+
them.
|
|
357
|
+
- **Read in this session** (`read`): today's files / memories / urls folds (`bodySections`), minus the memories the
|
|
358
|
+
start section shows. Its meta: held (not struck) and out (forgotten or dropped); its tokens the held items'.
|
|
359
|
+
- **Conversation** (`talk`): one row at section level, "Conversation · N turns ~X" (`headSections` still returns the
|
|
360
|
+
section; `headTemplate` draws it headerless, no fold; never lit, so dim in a turn lens),
|
|
361
|
+
`ctxTokens − Σ parts − Σ held items' tokens` (the read
|
|
362
|
+
section's and the start memories' reads), shown only when `ctxTokens` is known and the rest is > 0. Mixed units,
|
|
363
|
+
accepted: parts and items are chars/4, `ctxTokens` the server's count or chi's estimate (which on a chat host leaves
|
|
364
|
+
the tool schemas out, so without server usage the rest can go negative and the row hides); the "~" says so.
|
|
365
|
+
|
|
366
|
+
**Held twice.** A start memory row whose ops include `read` is held twice: in the prompt and in a read's output. The
|
|
367
|
+
session lens tags it `held twice` (warn tokens); a turn lens whose items read it lights it amber with a note under it:
|
|
368
|
+
"read again in this turn: already in the prompt, held twice (+X)". A lens lights a merged row by any of its merged
|
|
369
|
+
keys (`lensTouched`), and a part-only start row (no merged item, e.g. `x@system`) by its bare name too: a turn's rows
|
|
370
|
+
come from tool titles, which carry no scope, so in a turn lens a project `x` read lights a system `x`'s own row (lit,
|
|
371
|
+
not held twice: that row holds no read). A row with a merged item lights by its items' keys only. A turn lens counts
|
|
372
|
+
new over `headItems` (the set as the head view sees it: another scope's read is a plain read, not the prompt's), so a
|
|
373
|
+
project `x` first read beside a system `x` preload is new. It never counts a prompt memory as new (`promptKeys`, out of `turnLens`'s list). A forget or a
|
|
374
|
+
drop strikes the row where it stands (today's state words); the server knows an item's state now, not the turn that
|
|
375
|
+
changed it, so a turn lens has no forget count.
|
|
376
|
+
|
|
377
|
+
**Section folds.** Each section header folds (`data-ws="section"`), per session (`chi_ws_sections_folded:<session>`,
|
|
378
|
+
`session_prefs.js`); none stored: all open. Conversation has no header to fold: a stored `talk` (an older page's) is
|
|
379
|
+
ignored (`foldedSections`) and the next toggle writes the list without it. Folded, a section shows only the rows the lens lights (the read section's
|
|
380
|
+
lit members flat, without their inner groups). The header carries no size (the name, the lens, the ring
|
|
381
|
+
and ×: one line on a phone at 390 px); the line under it does. The session lens's: "in chi's head now · ~X of Y"
|
|
382
|
+
(`headLine`: X `ctxTokens`, Y the window; no "of Y" without one). Without parts or without `ctxTokens` that line is
|
|
383
|
+
the size line instead, "N items · ctx N %" (`.ws-size-line`), so the list never lacks a size; a turn lens has its
|
|
384
|
+
touched line only. The tokens-change check (`tokenText`) compares both lines' text. On a phone's sheet rows, section
|
|
385
|
+
headers and the lens buttons are 44 px targets.
|
|
386
|
+
|
|
387
|
+
**No parts** (an old session file, a worker before `prompt_parts`, a participant's list: `[]`): `headSections` is
|
|
388
|
+
null and the list is the flat files / memories / urls one with the lens unchanged. A turn end's `?tail=1` from an
|
|
389
|
+
older live worker leaves the key out: the page keeps the parts it has (`session_fields.js`: unknown is not none).
|
|
390
|
+
|
|
319
391
|
A state is the item's state now, not when its turn ran. A state change never refolds and never moves a line: the
|
|
320
392
|
rail's line key carries the label's state and its forgotten count, which are patched in place.
|
|
321
393
|
|
data/docs/plugins.md
CHANGED
|
@@ -1248,7 +1248,7 @@ ctx.sessions.stop(id) # one of this session's own children
|
|
|
1248
1248
|
- `send(id, text)` sends a user message to a session (an id or a unique
|
|
1249
1249
|
prefix); it runs as a turn, and an idle session is woken. A session its
|
|
1250
1250
|
owner stopped or archived is not: `Error` (`session_stopped` /
|
|
1251
|
-
`session_archived`), nothing sent. It waits up to
|
|
1251
|
+
`session_archived`), nothing sent; nor one being deleted (`session_deleting`). It waits up to
|
|
1252
1252
|
5 s for the session's worker, so call it from an anytime command or a
|
|
1253
1253
|
thread of your own, never from a tool or hook of a running turn. A
|
|
1254
1254
|
session a `--non-interactive` one-shot has can't take it.
|
data/docs/releasing.md
CHANGED
|
@@ -76,7 +76,7 @@ as the GitHub release body.
|
|
|
76
76
|
| `rake lint` / `rake lint:fix` | RuboCop over the repo (must report no offenses; CI runs it) / its safe autocorrect (`rubocop -a`). |
|
|
77
77
|
| `rake gem:validate`, `gem:build`, `gem:install`, `gem:clean` | Check the gemspec; build the gem into `pkg/`; build and install it locally; remove the built gems. |
|
|
78
78
|
| `rake release:draft_changelog` | A draft Unreleased section from the commit subjects since the last tag, grouped. Stdout only. |
|
|
79
|
-
| `rake release:bump[X.Y.Z]` | VERSION, the system manifest, Gemfile.lock, CHANGELOG, a compatibility corpus at `spec/compat/X.Y.Z/` written through the current state writers (with `wire/`: a real Engine and Bridge's replies, recorded twice and refused if the two differ), refreshed `spec/shared/compat_wire/*.json` fixtures, and `requires_chi: ">= X.Y.Z"` for each bundle marked `requires_chi_next` (the marker dropped), then a profile left below a member's `requires_chi` raised to it, with a patch bump of its version (none when it moved since the last tag) and named in the CHANGELOG's "Update with `chi update`" line, and each entry an `# Unreleased` comment in `Plugin::Api::SINCE` or `Manifest::SINCE` names moved into the table at X.Y.Z (the comment dropped). No commit; commit the corpus and
|
|
79
|
+
| `rake release:bump[X.Y.Z]` | VERSION, the system manifest, Gemfile.lock, CHANGELOG, a compatibility corpus at `spec/compat/X.Y.Z/` written through the current state writers (with `wire/`: a real Engine and Bridge's replies, recorded twice and refused if the two differ), refreshed `spec/shared/compat_wire/*.json` fixtures, `spec/web/public/exports_baseline.json` rebuilt from the public modules, and `requires_chi: ">= X.Y.Z"` for each bundle marked `requires_chi_next` (the marker dropped), then a profile left below a member's `requires_chi` raised to it, with a patch bump of its version (none when it moved since the last tag) and named in the CHANGELOG's "Update with `chi update`" line, and each entry an `# Unreleased` comment in `Plugin::Api::SINCE` or `Manifest::SINCE` names moved into the table at X.Y.Z (the comment dropped). No commit; commit the corpus, fixtures and baseline with the release. |
|
|
80
80
|
| `rake release:check` | Clean tracked tree, VERSION == system bundle, a CHANGELOG section, no `requires_chi_next` left, no `# Unreleased` comment left in `Plugin::Api::SINCE` or `Manifest::SINCE`, `bundles:check`, `rake lint` (RuboCop) + `npm run lint` (the web frontend's ESLint), rspec (both roots: `spec` and the bundles' own `spec/`) + `rake bundles:specs` + npm test, `gem build`, then a clean install into a temp GEM_HOME that runs `chi --version`, `chi self` and `chi bundle list` with a temp HOME. Needs the network (gem dependencies). |
|
|
81
81
|
| `rake release:notes[X.Y.Z]` | Prints the CHANGELOG section (default: the current VERSION). |
|
|
82
82
|
|
|
@@ -119,7 +119,8 @@ The agent does each step and stops where the user has to say yes.
|
|
|
119
119
|
`spec/compat_spec.rb` names it, and the shim goes (or its date moves)
|
|
120
120
|
before the release. The bump also refreshes `spec/shared/compat_wire/*.json`
|
|
121
121
|
by running `UPDATE_COMPAT_WIRE=1 bundle exec rspec spec/compat/wire_readers_spec.rb`;
|
|
122
|
-
|
|
122
|
+
rebuilds `spec/web/public/exports_baseline.json` from every public module
|
|
123
|
+
except `vendor/`; commit both with the release. If either refresh fails, the
|
|
123
124
|
bump is already written; follow its rerun command before reviewing or committing.
|
|
124
125
|
5. **Check.** Add all release files, including the new compatibility corpus, then run it:
|
|
125
126
|
`git add -A && git commit -m "Release X.Y.Z"` and `bundle exec rake release:check`.
|
data/docs/sessions.md
CHANGED
|
@@ -25,13 +25,13 @@ A session is deleted if **expired by age OR overflow by count** (unless `keep_st
|
|
|
25
25
|
|
|
26
26
|
**Worker idle exit:** a background worker (plain `chi`, Web UI sessions) exits after `SAMAGOTCHI_SESSION_IDLE_EXIT_MINUTES` (`session.idle_exit_minutes`, default `30`, `0`=never) with no turn running or queued, no client on its stream (an open web tab or attached terminal keeps it), no reminder registered, no background task it watches for a [finish wake](internals/background-tasks.md#finish-wake) still running or waiting for its wake turn (with `session.task_wakes: wake`; not one whose turn you stopped) and no continue offer (the step-limit question) waiting for an answer. It removes `bridge.json` and frees `owner.lock`; the next prompt or `--attach` wakes a new worker (`WorkerIdleExit`, `WorkerBoot.run_session_loop`). As its Bridge stops, the worker marks the lock leaving (`OwnerLock#mark_leaving`: `leaving_at`, and `leave_wait`, its `recap.timeout`), since it keeps the lock while it writes the recap on leave: an `--attach` or `--resume` meanwhile (here, or a remote one through chi web's wake) prints `(waiting for the session to finish its recap…)` (`LaunchMode::RECAP_WAIT`) and waits for the release, up to that budget plus `OwnerLock::LEAVE_MARGIN` (5 s), before starting the new worker (`OwnerLock.await_release`). A lock held by a worker that isn't leaving (a live one, a stuck one) is left as before. A client can also ask the worker to exit right away (Bridge `POST /session/:id/exit`; `/exit` in an attached terminal does, `/detach` doesn't): the same rules apply without the timeout (even with `0`), and the asker's own stream doesn't count. The reply names what keeps it up (for background tasks, which ones and how to stop them). When every hold is one the user can stop — reminders, a watched task still running, a delegate with a live worker — the 409 also carries `holds: [{kind:, items: [{id:, label:, detail:}]}]` (a reminder's detail is its schedule, `every 20m`/`every 1h`, `, due now` when it is already due), and an attached terminal asks what to do with them; its "stop them and exit" posts `{"stop": "all"}`, which clears the reminders, stops those tasks (`TaskRuntime.stop_task`, as `task_stop`) and stops those children (`SessionManager.stop_session`) before leaving, re-checking first that nothing the user can't stop appeared meanwhile (`HoldStop`). A delegate counts only for that ask: it never holds the idle exit, and an exit that deletes or archives the session does not ask about it. The session's status stays as it was, not `stopped`. With `"restart": true` (a worker whose sidecar lists the `restart` feature) the worker hands the session to a new worker on the newest chi installed: it leaves, then starts its successor once its lock is free, keeping even an empty session and writing no recap. Clients' streams don't hold a restart (a web tab and an attached terminal reconnect to the new worker); what would be lost does: a turn running or queued, a continue offer, a question or approval waiting, a `/btw` (or another anytime command) still running, a delegate's approval relay open or settled in the last 10 minutes, and background tasks this conversation started that still run (`WorkerIdleExit#hold_for_restart`; 409 `held` with `reason`). Reminders go along: as it leaves, the worker writes them to `<id>/reminders.json` (0600: `session_id`, `written_at`, and each reminder's id, name, description, interval and next fire as wall-clock time; `ReminderCarry`), and its successor reads and deletes the file as it starts, before its idle scheduler runs. A restored reminder keeps its id and schedule; one that came due meanwhile fires once at once, and one further ahead than its interval (a clock that jumped) is due one interval from now. The file counts only for the same session within 2 minutes of `written_at`, and not once the session is stopped: otherwise it is deleted unread (log `reminders_carry_dropped`, at warn unless the session was stopped). A stop that lands while the worker leaves for a restart wins: the worker writes no file, and no successor starts (`WorkerBoot.run_session_loop`, log `restart_dropped`). So does one that lands as it leaves any other way (an idle exit, `/exit`, a signal) with input queued or delegate reports waiting: no new worker un-stops it (log `respawn_dropped`), and what waits stays for the next start. A person's send after the stop (chi send, a web tab, a terminal) still un-stops it, as a person's send always does (see *Who may wake a session* below): one that reaches a leaving worker clears the stop, so the leave's new worker runs it (log `send_unstopped_leaving`); an archive deletes the file of each session it archives. Once an exit or restart is taken (claimed before a stop-all stops anything), the first one decides how the worker leaves: a later request of the same kind is answered as that exit, one of another kind (a stop-all from another terminal after a restart, chi web's "Restart workers" after a `/exit`) gets 409 `held` with `reason` `leaving_exit`, `leaving_delete` or `leaving_restart`, and a restart says it was refused rather than "restarted". A write that fails keeps the worker up with its reminders (log `reminders_carry_failed`), and the caller reports no new worker. A reminder already due when the restart is asked runs its turn first, so the restart's wait (10 s) may report no new worker yet though the hand-off follows. A worker from before this still refuses a restart for its reminders (409 `reminders`). Only an asked restart carries them: the fallback's TERM (a worker that can't be asked, below), a stop, an idle exit (which reminders hold anyway) and a crash drop them as before. What lives only in the worker's memory goes: the event history a late client replays, the kept `/btw` answers, a plugin's in-memory state.
|
|
27
27
|
|
|
28
|
-
**Empty sessions:** a session nothing happened in is deleted when it is left, so `chi` → `/exit` leaves no trace. Empty means: no messages, no turn tried (a failed turn leaves a `last_prompt` and keeps it), no memory used, no pending question, nothing in `input/`, `notes/` or `images/`, nothing in its dir beyond the worker's skeleton, mode `assist`, and the default model. A session on another model (`/model`, `--model`) counts as prepared and stays (`SessionManager.discardable?`). The worker checks as it idle-exits or leaves on a client's request and deletes it once its lock is free, checking again first. The attached `/exit` then says `Detached; the session is empty: it will be discarded if nothing arrives before its worker stops.` (a note or prompt landing first keeps it). The retention sweep catches those killed first: empty sessions over an hour old with no live owner, whatever `DAYS`/`MAX`, and skeleton-only dirs with no `*.json` (removed as a delete removes, every session store, under the session's lock: a worker or a start that took the session since the check keeps it, and so does one whose file or content was written meanwhile, read again under that lock). `session.keep_empty: true` (env `SAMAGOTCHI_SESSION_KEEP_EMPTY`) turns all of it off.
|
|
28
|
+
**Empty sessions:** a session nothing happened in is deleted when it is left, so `chi` → `/exit` leaves no trace. Empty means: no messages, no turn tried (a failed turn leaves a `last_prompt` and keeps it), no memory used, no pending question, nothing in `input/`, `notes/` or `images/`, nothing in its dir beyond the worker's skeleton, mode `assist`, and the default model. A session on another model (`/model`, `--model`) counts as prepared and stays (`SessionManager.discardable?`). The worker checks as it idle-exits or leaves on a client's request and deletes it once its lock is free, checking again first and once more under the delete's lock (a prompt or note that went in before that keeps it). The attached `/exit` then says `Detached; the session is empty: it will be discarded if nothing arrives before its worker stops.` (a note or prompt landing first keeps it). The retention sweep catches those killed first: empty sessions over an hour old with no live owner, whatever `DAYS`/`MAX`, and skeleton-only dirs with no `*.json` (removed as a delete removes, every session store, under the session's lock: a worker or a start that took the session since the check keeps it, and so does one whose file or content was written meanwhile, read again under that lock). `session.keep_empty: true` (env `SAMAGOTCHI_SESSION_KEEP_EMPTY`) turns all of it off.
|
|
29
29
|
|
|
30
30
|
**Participants:** a session its owner invited participants into (`chi share`, see [CLI: Participants](cli.md#participants)) has two more files in its dir, neither in the session JSON: `participants.json` (0600), who is or was invited (`{participants: [{id, kind, name, role, added_at, expires_at, removed_at}]}`, never a token), which chi web and `chi share` write and the worker reads (`Participants.read`); and `participants.jsonl` (0600, append-only), the audit trail (grants issued, revoked and expired, each new peer, refused routes). A session nobody was invited to has neither. A continue, a fork or a delegate starts with no participants. Archiving or deleting the session revokes its links. See [internals/participants.md](internals/participants.md).
|
|
31
31
|
|
|
32
32
|
**Always attached:** every interactive `chi` (plain, `-p`, `--resume ID`, `--attach ID`, `chi scratch`) runs its session in a background worker and attaches to it; there is no setting for it. The worker runs in the session's `working_directory`, so `!commands` and tools see the directory the session was started in. Only `chi -p TEXT --non-interactive` runs its one turn in this process; while it does, the session can't be attached ("in use by a one-turn chi --non-interactive run or an older chi's terminal"). See [CLI: Sharing a session](cli.md#sharing-a-session).
|
|
33
33
|
|
|
34
|
-
**Who may wake a session:** every turn delivery names its sender (`SessionManager.deliver_turn` requires `client_id`), and the sender's kind picks what it may do to the worker (`ClientId.wake_kind`, `SessionInbox::WakePolicy.for_sender`). A person — `chi send`, a web tab, an attached terminal — starts an idle session, un-stops a stopped one and brings back an archived link. A schedule's firing, a plugin's `ctx.sessions.send`, a `delegate` follow-up, a participant's turn and any sender chi doesn't name start an idle session only: a session its owner stopped or archived refuses them (409 `session_stopped`, "the session is stopped; only its owner's message starts it again", or `session_archived`, "…brings it back"), nothing written. A schedule counts that as a skip (and skips a stopped session at its check, [scheduling.md](scheduling.md)); `delegate` says it as `Error: session <id8> refused: …`; a plugin gets `Error`. A turn already handed to a live worker is that worker's, as before. chi web's owner turn and command routes name a body that carries no `client_id` as `web:unnamed` (a web tab's rights).
|
|
34
|
+
**Who may wake a session:** every turn delivery names its sender (`SessionManager.deliver_turn` requires `client_id`), and the sender's kind picks what it may do to the worker (`ClientId.wake_kind`, `SessionInbox::WakePolicy.for_sender`). A person — `chi send`, a web tab, an attached terminal — starts an idle session, un-stops a stopped one and brings back an archived link. Nobody's message goes into a session being deleted (409 `session_deleting`, *Deleting a session* above). A schedule's firing, a plugin's `ctx.sessions.send`, a `delegate` follow-up, a participant's turn and any sender chi doesn't name start an idle session only: a session its owner stopped or archived refuses them (409 `session_stopped`, "the session is stopped; only its owner's message starts it again", or `session_archived`, "…brings it back"), nothing written. A schedule counts that as a skip (and skips a stopped session at its check, [scheduling.md](scheduling.md)); `delegate` says it as `Error: session <id8> refused: …`; a plugin gets `Error`. A turn already handed to a live worker is that worker's, as before. chi web's owner turn and command routes name a body that carries no `client_id` as `web:unnamed` (a web tab's rights).
|
|
35
35
|
|
|
36
36
|
**Which chi a worker runs:** a new or woken worker runs the newest chi installed for this Ruby (`gem 'samagotchi', '>= 0.a'`, prereleases count), whoever starts it: a `chi web` or terminal still on an older chi starts it on the newest one, so a stale process doesn't spread old code. A worker already running keeps its version until it is restarted. Should the newest install fail to load, the worker runs the starter's own version and logs `boot_fallback` (its stdio is `/dev/null`). Under `bundle exec` the worker drops Bundler's env first, so it activates the newest gem too. Two consequences: a wrapper pin (`chi _0.17.0_ web`) pins only that process, not the workers it starts; and a source checkout (`bin/chi` in a worktree, `bundle exec`) starts its workers on its own `lib/`, but a session it made that is later woken by an installed chi (`chi web`, `chi send`) runs the installed code. The names an older starter hands a newer worker (the boot line, its env keys, `input/` files, the session JSON fields and the Bridge routes sessions use on each other) are pinned in `spec/worker_contract_spec.rb`. A chi newer than 0.130.0 keeps the top-level keys it doesn't know (a newer chi's fields) when it saves a session, after its own, and doesn't act on them; `written_by` names the chi that saved the file last, and a worker woken on a file a newer chi saved logs `newer_writer`. chi 0.130.0 and older drop those keys: a session a newer chi made loses its newer fields when an older chi wakes or saves it (for example `chi --attach` from a project whose Ruby has an older chi). Keep the chi in every Ruby you run it from newer than 0.130.0.
|
|
37
37
|
|
|
@@ -43,7 +43,7 @@ A new session field is one `Session::FIELDS` row, plus a `SessionSetup` member w
|
|
|
43
43
|
|
|
44
44
|
**Stopping a worker:** `chi sessions stop ID` marks the session stopped (an `<id>/stopped` file holding when, `{"at"}`, not a session.json field, which a worker saving at that moment would write over; a resume removes it), sends its worker TERM, then CONT (a stopped worker, SIGSTOP or Ctrl-Z, runs its TERM handler only once continued, so it leaves at once instead of outliving the wait), and waits (up to 10 s) until the worker has let go of `owner.lock`. A running turn is canceled over the Bridge first, with reason `session_stopped` (the turn's line ends "(session stopped)", its note says `cancelled (session-stopped)`, and a command it was running says "stopped as the session was stopped"; a bare signal to the worker makes it "stopped by a signal to chi"; an older worker takes the reason as `manual`); the TERM stops whatever still runs as a Stop with reason `signal` and saves it (a spawned worker traps TERM, HUP and INT: `WorkerSignals`; a turn not ended within 3 s, 0.5 s after a stop or a second signal, is cut and the session saved as it was), and a stopped worker still saves its kept turn, since the marker, not the saved status, says stopped. Any TERM, HUP or INT does the same to a worker outside a stop: it leaves (log `worker stop reason=signal`) and the next send wakes a new one, so a `chi --resume ID` right after spawns a fresh worker. That is also how to restart a worker still running an older chi, which the attached terminal reports when a command or a question dismiss gets a 404, and the web when an answer, a dismiss, a command or a cancel does (`501 not_supported`; `BridgeClient.stale_worker_message`). A command this chi has that the older worker doesn't (`/llm-context`, the web's ⚙ panel, against a 0.39.0 worker) says the same, not `not a session command` (`SessionCommandCatalog.builtin_name`); a typo keeps its `400 unknown_command`. The web's `POST /api/sessions/:id/stop` waits the same way, for 2 s (the page's Stop shows the stop at once), or for the body's `wait` up to the same 10 s (`SessionManager::STOP_WAIT`): `chi --remote NAME sessions stop` sends it, so it waits as long as here. Before that stop, the page's `stop session` button asks what the worker still has that the user can stop: `GET /api/sessions/:id/holds` (owner-only) answers the worker's `holds` — the same list the exit ask's 409 carries — always an array, empty when there is no live worker, one from before the route, or one that did not answer. With something, a sheet (a bottom sheet on a phone, a popover at the button otherwise — `stop_sheet.js`) lists them, at most three of a kind named and `+N more`, and offers **Stop all** (`POST /api/sessions/:id/holds/stop` → `HoldStop#stop_all`, then the stop), **Stop session only** (the stop exactly as it was) or **Cancel**. Nothing to ask about is the plain confirm, one tap as before. Both buttons stay because a stop only TERMs the worker: its reminders die with it (a stop also deletes a restart's `reminders.json` no successor took yet, so a later resume doesn't bring them back), while a background task and a delegate are their own processes and keep running. A command sent during a turn that waits for its end (`/model X`, `!cmd`; see *Typing during a turn* in [cli.md](cli.md)) and hasn't run when the worker leaves (a stop, a crash) is answered `command_ran {status: "dropped"}`, so no UI keeps showing it waiting.
|
|
45
45
|
|
|
46
|
-
**Deleting a session:** `chi sessions delete ID...`, `/exit --delete` in a terminal and the Web UI's delete all go through `SessionManager.delete_session`: it resolves a unique prefix, removes `<id>.json` and the whole `<id>/` dir, and returns what it removed. A session a one-turn `chi --non-interactive` run has (`owner.lock` kind `tui`) is always refused. One a worker runs is refused unless the caller asks to stop it: then it stops the worker as `chi sessions stop` does and deletes once `owner.lock` is free (`--force` on the CLI, 10 s; the web page always, 2 s; `/exit --delete` after the worker agreed to exit, 10 s). A worker that outlives the wait leaves the session in place. A session whose worker is being started (the `<id>/starting` marker) is refused or stopped the same way, and the files go while the delete holds `owner.lock`, so a worker can't take the session in the middle; a worker that still had it loaded doesn't write it back. The web's route is `DELETE /api/sessions/:id?force=true` (the page sends `force`; without it a live worker's session is 409 `worker_running`, as the CLI without `--force`; 200 `{status: "deleted", session_id, stopped, unarchived, moved_back}`; `deleted` and `left_running` too; 409 with the refusal's reason as its code; 404). A schedule's target, anchor or head is refused (`scheduled`, naming the schedule): deleting a head would make the schedule fall back to an archived link. A user's delete (these three, `revive_previous:` and `refuse_continuing:` on `delete_session`) also knows about chains (`SessionChain::Delete`, *Session chains* → Deleting a link): it is refused while a continue of the session, or of the previous link it would bring back, is under way (`continuing`), and deleting a chain's newest link undoes its continue (D2/D5 below), the ids it brought back in `unarchived` and the delegates it gave back in `moved_back`. A previous link brought back is aged for retention from then on (`unarchived_at`) and has no participants (the archive ended them, and an unarchive doesn't bring them back). The scratch cleanup, the empty-session discard, the failed-continue rollback and a schedule's prune delete plainly; the retention sweep removes files directly (`remove_files`).
|
|
46
|
+
**Deleting a session:** `chi sessions delete ID...`, `/exit --delete` in a terminal and the Web UI's delete all go through `SessionManager.delete_session`: it resolves a unique prefix, removes `<id>.json` and the whole `<id>/` dir, and returns what it removed. A session a one-turn `chi --non-interactive` run has (`owner.lock` kind `tui`) is always refused. One a worker runs is refused unless the caller asks to stop it: then it stops the worker as `chi sessions stop` does and deletes once `owner.lock` is free (`--force` on the CLI, 10 s; the web page always, 2 s; `/exit --delete` after the worker agreed to exit, 10 s). A worker that outlives the wait leaves the session in place. A session whose worker is being started (the `<id>/starting` marker) is refused or stopped the same way, and the files go while the delete holds `owner.lock`, so a worker can't take the session in the middle; a worker that still had it loaded doesn't write it back. While the delete holds it (kind `deleting`), every delivery is refused: a message (`chi send`, the web, a schedule, a delegate, a plugin, a participant) gets 409 `session_deleting`, "the session is being deleted", and a send that read the session before the lock and wrote after it takes its file back and says the same (unless a worker took the file meanwhile: then it is delivered); a note is refused as for a gone session, and a delegate's ring, a push and a fresh verdict are not written. The web's route is `DELETE /api/sessions/:id?force=true` (the page sends `force`; without it a live worker's session is 409 `worker_running`, as the CLI without `--force`; 200 `{status: "deleted", session_id, stopped, unarchived, moved_back}`; `deleted` and `left_running` too; 409 with the refusal's reason as its code; 404). A schedule's target, anchor or head is refused (`scheduled`, naming the schedule): deleting a head would make the schedule fall back to an archived link. A user's delete (these three, `revive_previous:` and `refuse_continuing:` on `delete_session`) also knows about chains (`SessionChain::Delete`, *Session chains* → Deleting a link): it is refused while a continue of the session, or of the previous link it would bring back, is under way (`continuing`), and deleting a chain's newest link undoes its continue (D2/D5 below), the ids it brought back in `unarchived` and the delegates it gave back in `moved_back`. A previous link brought back is aged for retention from then on (`unarchived_at`) and has no participants (the archive ended them, and an unarchive doesn't bring them back). The scratch cleanup, the empty-session discard, the failed-continue rollback and a schedule's prune delete plainly; the retention sweep removes files directly (`remove_files`).
|
|
47
47
|
|
|
48
48
|
<a id="archiving-a-session"></a>**Archiving a session:** `chi sessions archive ID...`, `/archive` in a terminal and the Web UI's `archive` go through `SessionManager.archive_session`: it writes `<id>/archived` (`{"archived_at": …}`; not a session.json field, which every save rewrites) for the session and its delegated children. `Session.list` leaves archived sessions out unless `include_archived:`, and everything built on it follows: `chi sessions list` (`--archived` shows them, `[archived]`), the summaries (`--live`, json/tsv, the desktop panel, the agent's `list_sessions`) and the retention prune, which neither deletes nor counts them against `max_count`. `children_of` (max_children, `delegate_result`) still sees them, and `--resume`/`--attach ID`, `chi send`/`chi note ID` reach them as before, except that `chi send` and `chi note` to a link that was continued go to its chain's newest link (*Session chains*). Refused: a turn running in the session or in one of its children (naming the child; 409 `busy` on the web), a prompt queued in `input/` (it would run on the next resume) or a live worker's step-limit question still open, in it or a child (409 `busy` too), a one-turn `chi --non-interactive` run owning it (`owned_by_tui`), a `chi scratch` session (`scratch`). A live idle worker is stopped first, and the marker is written even if it is still shutting down. Input a human typed brings a session back (`{"unarchived_at": …}`): a prompt from the web, an attached terminal or `chi send` (origin `web:*`, `tui:*`, `cli:send`, its own first prompt: `spawn:first`; input naming no sender doesn't), steering merged into a running turn, a `/continue` answer or a question answered (the step-limit question too); a delegate's follow-up, a plugin's turn, a reminder, the idle recap, a note and just opening it don't. A child's input brings only the child back. The retention sweep ages an unarchived session from when it was unarchived, so unarchiving an old session doesn't let the next sweep take it. `/archive` leaves the session first, as `/exit` does, then archives it: in an attached terminal the worker is asked to exit (one that stays up for another UI is stopped by the archive; a running turn, a queued prompt or an open step-limit question refuses it), and an empty session is discarded instead; `chi scratch` refuses it. Typed while a turn runs, `/archive` waits for the turn's end (an attached terminal for the commands queued behind it too) and then archives. `chi sessions unarchive ID...` and the web's `unarchive` bring back the whole family. Web routes: `POST /api/sessions/:id/archive` (200 `{status, session_id, archived, stopped, discarded}`, ids) and `POST /api/sessions/:id/unarchive` (200 `{status, session_id, unarchived}`). The session hub and `GET /api/sessions` keep archived sessions, `archived: true` in their summaries: the page leaves them out of the strip, its count and the list at render, and the `archived` toggle beside the all-sessions search shows them, dimmed with an `archived` badge. The info bar marks a session whose live worker runs an older chi than the newest installed (`worker_version` in its summary): `chi 0.18.1 · Restart`, which asks to confirm and calls `POST /api/sessions/:id/restart` (a refusal's reason shows in a toast); a worker from before restarts shows `chi sessions stop ID` instead. The info bar reads `continue → · archive · stop · delete` (`unarchive` on an archived one; no `continue →` on a link continued already, see *Session chains*; `continue →` is a plain button like `archive`, in the accent on an archived session, where it is the thing to do); archiving the open session stays on it, with an Undo toast.
|
|
49
49
|
|
|
@@ -141,6 +141,7 @@ chi sessions clean --dry-run --days 7 # test sessions older than 7 da
|
|
|
141
141
|
| `project_id` | A marked project's id (its `.chi/project.yml`'s `id:`), saved beside `project_root`: the session's project context sources are keyed by it, so they follow a moved folder. Absent for any other project. | creation |
|
|
142
142
|
| `preloaded_memory_names`, `muted_memory_names` | `--memory` and `--mute`, written before the worker starts so a respawn builds the same prompt; copied by a fork and a continue. A fork drops the reserved `system/delegated` memory so its `parent_id` does not make it a delegate; a continuation of a delegate child drops it because the new link is not a delegate. | creation |
|
|
143
143
|
| `prompt_notes` | The model notes the system prompt carried at its last build (`[{name, scope, chars, digest}]`, see [Memory](memory.md#model-notes)). | the Engine, at each prompt build |
|
|
144
|
+
| `prompt_parts` | The sizes of the parts the system prompt was made of at its last build (`[{kind, label, chars, tokens, ref, scope?}]`: a `tools` part first, then one per memory, file and plugin section in prompt order, the indexes one per scope; tokens at `chars / 4`; no text). `scope` is a memory part's, `project` or `system` (identity `system`, a model note its own, a preload the scope that answered its read); other parts and an older file leave it out, and the page then matches the part to the set's memory by name alone. A `/model` switch records `[]` until the next build. The web's head view lists them; an older file or worker has none and reads as `[]` (a missing field is the old case, the page draws without the part rows). | the Engine, at each prompt build |
|
|
144
145
|
| `parent_id` | The session that delegated this one or forked it (`ctx.sessions.fork`); `null` otherwise. See [Delegating](#delegating). | `SessionManager.spawn_session`; `ChildMove` writes a `parent.json` beside it instead of this file |
|
|
145
146
|
| `scratch` | A `chi scratch` session, deleted when its terminal leaves. | creation |
|
|
146
147
|
| `last_turn` | How the last turn ended (`LastTurn`), for a parent's wait and the web's notifications. | the Engine, at a turn's end |
|
|
@@ -385,7 +386,7 @@ A session can **continue** an earlier one: "the next run of the same routine" (a
|
|
|
385
386
|
- **The page:** the info bar's `continue →` continues the open session (`continues: <id>, idle: true`; it reads `continuing…` through the recap wait) and opens the new link with an opener in the composer, not sent (a draft written in this session stays instead; one carried over from another session or the start page gives way to the opener, and the toast's **Restore draft** brings it back): the previous link's own first typed message when that link continues one (the 201's `opener`; a `!shell` line isn't taken), else `Continue where we left off.`. So whatever you sent on the last link comes back on the next one, and editing it once changes it for every later link; the previous link is archived, a toast says so (`Continued 3fa2c1d0 in 4b7e9a01; 3fa2c1d0 is archived; 1 open delegate moved`), and a moved delegate's card folds under the new link. When the previous link's model's host is gone the link starts on the default model and the toast carries the server's `model_warning` too, and then stays until closed. A fresh link (one with no turn yet, however it was made: `continue →`, `chi send --new --continues`, a reload) shows the model picker in its composer with the link's model, until its first turn starts (a failed or canceled first turn ends it too); a pick runs `/model <name>` in the link (a command bubble; the info bar follows) and changes neither the start page's remembered model nor its Recent list, and a Send right after it waits for the `/model` to be taken. A link a one-turn `chi --non-interactive` run has, or one continued already, shows none. A link continued already has no `continue →`: its `→` link goes to the next link (a stale page's continue answered 409 `continued` opens `next_id`). A continue refused for open delegates that can't move shows a toast that names each one (its preview and what the server says to do: `older chi worker 0.46.1; restart it`, `in use by a one-turn chi --non-interactive run or an older chi's terminal; let it finish`), each a link to its page; any other refusal shows the server's words. The info bar of a link carries `← 2026-10-08` (the previous link's day) and, on an earlier link, `2026-10-10 →`, each a link with its id, its full start (`2026-10-10 14:32`) and its preview in the tooltip; a neighbour that started on the open link's own day shows its time instead (`← 09:12`, `14:32 →`). A link made by `continue →` inherits the previous link's preview (and its title, if it has one) when it is created, so its card keeps its chain's title whatever opener it is sent, and its top bar and browser tab show its card's title. A link with a recap of its own reads its auto title, else its recap's first sentence, instead (a link without one reads its chain's name, and a first link's recap names its chain). A link whose title is the opener and nothing else (a `chi send --new --continues` link whose first message is `Continue where we left off.`) shows its chain's first link's title instead, on its card, in the popover and in its info bar's title line, display only (its messages and data keep the opener; its own title when the first link is gone). The lists fold a chain into the card of its latest listed link, whatever the earlier links' archived state (typing in an archived link brings it back, folded there still), their delegates with them: the card's `↩ #N` chip (`#N of M` when later links aren't listed; its tooltip `Session chain: link N of M`) opens a popover of the other links, newest first (`#N`, its date, with its time (`2026-10-17 14:32`) when another link of the chain started the same day, its own title when it differs from the card's (a link inherits its chain's, so mostly it doesn't), else its recap's first sentence, else its preview, `archived`), a click opens one; the chip shows a live dot or `waiting` for a link that has a worker or waits on the user, and a waiting link puts its chain's card first. All sessions folds nothing while a search is typed or the `archived` toggle is on: every link is a card of its own then, its chip `#N of M`, with its own delegates folded in, so a search finds an earlier link and its delegates.
|
|
386
387
|
- **CLI:** `chi send --new --continues (ID|PREFIX|last:ID) [--model M] [-m TEXT]` (see *Starting a session*).
|
|
387
388
|
- **Which link:** an id, a unique prefix, or `last:<id or prefix>`, the latest link of the chain that session is in. It walks the links that still exist: a deleted link in the middle (`chi sessions delete`, the retention sweep of an unarchived one) ends the walk before it, so `last:` of an earlier link then names that earlier link, and continuing it starts a second line beside the links after the gap; name a link after the gap instead. A trigger names the chain this way: a person's message to an archived link that nobody continued brings it back (a human's input), it doesn't continue the chain; an unattended sender's is refused (*Who may wake a session*). That is the rule: `chi send` and a note go to the chain's newest link (*Sending a message*, *Context notes*); the web composer, a participant's turn and `delegate(session:)` go to the link they name. One walker answers every one of these (`SessionChain::Links`: one session listing, archive flags read once; the earliest created successor wins a fork a hand edit made, a loop ends where it would repeat), with two rules on it, not unified on purpose: `last:` and a schedule take the chain's **end** (`Links#latest`: a continue refuses a link continued already, and a schedule never un-archives a chain you retired), `chi send` and a note the **first link not archived** (`Links#first_live`: a person's input goes where the chain is live, and brings back an archived end). A chain pruned by a schedule keeps its `anchor`: the kept window's oldest link still names a link that is gone, so the walk simply stops there; the page's chip counts from the surviving root (pruning renumbers the links) and its popover says `earlier links pruned` where the walk stops, rather than linking to a deleted session.
|
|
388
|
-
- **Deleting a link** (`SessionChain::Delete`; the CLI, the web and `/exit --delete`): a link of a chain is deleted alone by default, and what follows depends on where it is. **The newest link** (nobody continues it, it isn't archived itself, the link before it is archived) undoes its continue: the delegates the continue moved go back to the previous link, finished ones too (`continued_from.json`'s `moved_ids`, still under the link; without the record, its children whose `parent.json` says they came from the previous link), each with a note saying the link was deleted; every note waiting in the link but the continue's own goes back too (`NoteMove.give_back`); then the previous link and what the continue archived with it come back to the lists (without the record, the previous link alone). The previous link is **not started**: reports a moved-back delegate left wait for its next start. What dies with the link: its turns, context sources, objectives edits, session approvals and participant grants (the previous link kept its own copies). Every refusal comes before anything goes: the link's delegates that would go are checked too (a schedule on one, a one-turn run), and they and the link are removed (and the undo runs) only under their `owner.lock`s (kind deleting, taken without waiting, so a worker that took one refuses it); a moved delegate that can't go back (`ChildMove.unmovable`: an older chi's worker, a one-turn run) refuses it (`delegate_unmovable`, naming it), as does a worker that took the link after the stop. Deleting the links one after another undoes each continue by its own record. **A middle link** splits the chain (the earlier links stay archived, the later ones go on as their own chain); nothing is undone or re-linked. A link whose chain is all archived stays archived around the gap. **The link's own delegates** (any position) follow one rule, `SessionChain::Delete::DELEGATES`: a running one (a worker owns it or is starting for it, a one-turn run; a saved `running` with no worker is a crashed run, and goes) is left running with its whole subtree, its file untouched (its parent's id names a deleted session; its reports are refused as for any gone parent); every other node under the link goes, deepest first, before the link. A session in no chain (a link alone past a gap too) is deleted as before. **The web asks first**: for a chained session, chi web's delete sheet reads `GET /api/sessions/:id/delete_plan` (`:owner`; no query or body; no-store), `SessionChain::Delete::Preview` over the same `LinkPlan`/`ChainPlan` and checks the delete runs (`check_link!`, `check_chain!`): the link's place in the chain, what comes back and goes for each choice, and each choice's refusal now (a schedule on the chain, the link or a delegate that would go, a continue under way, a one-turn run, a moved delegate that can't go back and whether the page can stop it). One session listing walk per call; the page asks only for a chained session as the sheet opens. It takes and releases each link's continue lock (shared, as the delete does), creating its empty file where there was none, and writes nothing else; an unknown id is the usual 404. The moved count is each moved delegate with its subtree (they come back with it), and a `delegate_unmovable` 409 says `stoppable` itself.
|
|
389
|
+
- **Deleting a link** (`SessionChain::Delete`; the CLI, the web and `/exit --delete`): a link of a chain is deleted alone by default, and what follows depends on where it is. **The newest link** (nobody continues it, it isn't archived itself, the link before it is archived) undoes its continue: the delegates the continue moved go back to the previous link, finished ones too (`continued_from.json`'s `moved_ids`, still under the link; without the record, its children whose `parent.json` says they came from the previous link), each with a note saying the link was deleted; every note waiting in the link but the continue's own goes back too (`NoteMove.give_back`); then the previous link and what the continue archived with it come back to the lists (without the record, the previous link alone). The previous link is **not started**: reports a moved-back delegate left wait for its next start. What dies with the link: its turns, context sources, objectives edits, session approvals and participant grants (the previous link kept its own copies). Every refusal comes before anything goes: the link's delegates that would go are checked too (a schedule on one, a one-turn run), and they and the link are removed (and the undo runs) only under their `owner.lock`s (kind deleting, taken without waiting, so a worker that took one refuses it); a moved delegate that can't go back (`ChildMove.unmovable`: an older chi's worker, a one-turn run) refuses it (`delegate_unmovable`, naming it), as does a worker that took the link after the stop. Deleting the links one after another undoes each continue by its own record. **A middle link** splits the chain (the earlier links stay archived, the later ones go on as their own chain); nothing is undone or re-linked. A link whose chain is all archived stays archived around the gap. **The link's own delegates** (any position) follow one rule, `SessionChain::Delete::DELEGATES`: a running one (a worker owns it or is starting for it, a one-turn run; a saved `running` with no worker is a crashed run, and goes) is left running with its whole subtree, its file untouched (its parent's id names a deleted session; its reports are refused as for any gone parent); every other node under the link goes, deepest first, before the link. A session in no chain (a link alone past a gap too) is deleted as before. **The web asks first**: for a chained session, chi web's delete sheet reads `GET /api/sessions/:id/delete_plan` (`:owner`; no query or body; no-store), `SessionChain::Delete::Preview` over the same `LinkPlan`/`ChainPlan` and checks the delete runs (`check_link!`, `check_chain!`): the link's place in the chain, what comes back and goes for each choice, and each choice's refusal now (a schedule on the chain, the link or a delegate that would go, a continue under way, a one-turn run, a moved delegate that can't go back and whether the page can stop it). One session listing walk per call; the page asks only for a chained session as the sheet opens. It takes and releases each link's continue lock (shared, as the delete does), creating its empty file where there was none, and writes nothing else; an unknown id is the usual 404. The moved count is each moved delegate with its subtree (they come back with it), and a `delegate_unmovable` 409 says `stoppable` itself. Each choice carries a `digest` (`SessionChain::Delete.digest`: the sorted ids it deletes, leaves, revives and moves back); the sheet's DELETE sends it as `expect=`, and the delete compares it with the plan it runs (a link's under its holds, as `delete_link` starts; the chain's before its checks) and refuses `plan_changed` (409) before anything changes, a session no longer chained too. Without `expect` (the CLI, an older page) it deletes as it plans then. **The whole chain** (`chi sessions delete --chain`, `DELETE /api/sessions/:id/chain`, `SessionManager.delete_chain`): every link reachable from this one on its branch, newest first, each with its delegates by the same rule. Refused before anything goes when a schedule is on the chain (`chain_scheduled`) or on a delegate that would go (`scheduled`), a link or such a delegate is in a one-turn run, a continue of a link is under way (`continuing`), without `force` a link has a worker, or a link's worker outlives the stop's wait: every link is checked and stopped before the first is deleted, and each then goes under the owner locks of it and its delegates. A chain with a gap before this link reaches only the part after the gap: the earlier links stay archived (`cut_off: true`). A link refused part-way (a worker that took it after its stop) leaves it, its delegates and the earlier part of the chain whole, its new end back in the lists, and the result lists what was left.
|
|
389
390
|
|
|
390
391
|
## Schedules
|
|
391
392
|
|
|
@@ -555,5 +556,7 @@ the session; the message directs the user to `chi sessions stop ID`, then any pr
|
|
|
555
556
|
Reminders, a running `/btw`, and other in-memory worker state cannot be
|
|
556
557
|
checked and may be lost in this fallback. A stopped worker (SIGSTOP or
|
|
557
558
|
Ctrl-Z: `ps` state `T`) answers neither the ask nor a TERM, so a restart
|
|
558
|
-
refuses it at once, before asking, with its pid and `kill -CONT PID`.
|
|
559
|
+
refuses it at once, before asking, with its pid and `kill -CONT PID`. A
|
|
560
|
+
session whose stop is marked (stopped, or its worker being stopped) is refused
|
|
561
|
+
before any of this (`stop_marked`: no successor would come).
|
|
559
562
|
The web restart route behaves the same way.
|
data/docs/testing.md
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
bundle exec parallel_rspec -n 8 spec lib/samagotchi/bundles/*/spec # Ruby specs, both roots, in parallel
|
|
5
5
|
bundle exec rspec spec lib/samagotchi/bundles/*/spec # the same, plain
|
|
6
6
|
bundle exec rake bundles:specs # the shipped bundles' own specs, on the bundle test kit alone
|
|
7
|
-
npm test # web frontend specs
|
|
7
|
+
npm test # web frontend specs, including the new-module exports ratchet
|
|
8
8
|
npm run lint # web frontend: undefined names and unused imports (ESLint; CI runs it)
|
|
9
9
|
npm run e2e # web UI happy paths in Chromium, fake model (once: npx playwright install chromium)
|
|
10
10
|
npx playwright test spec/e2e/stage.spec.js # one e2e file (the root playwright.config.js is the suite's)
|
|
@@ -478,7 +478,9 @@ file's layer (any `foo/*.rb` → `spec/foo_golden_spec.rb` when there is one; `t
|
|
|
478
478
|
words the attached TUI prints, pick its `event_renderer` and `attached_loop` specs by a rule; `memory_bundle/*.rb`,
|
|
479
479
|
`bundle_command.rb`, `memory_paths.rb`, `model_overlay.rb` and the corpus's fixtures pick the bundle-state corpus). Changes to `tool_declarations.rb` and `system_prompt.rb` also pick the
|
|
480
480
|
effective-model, request, prompt-snapshot and full system-prompt goldens because they hash the request's prompt and
|
|
481
|
-
tools.
|
|
481
|
+
tools. Changes under `lib/samagotchi/worker/*.rb` also pick `spec/worker_spec.rb`, `spec/worker_*_spec.rb`,
|
|
482
|
+
`spec/web/app_session_settings_characterization_spec.rb` and `spec/require_cycle_spec.rb`. Then come the other name
|
|
483
|
+
matches (a spec named after several changed files first, e.g. `engine_toolkit_spec.rb` for `engine.rb` and
|
|
482
484
|
`toolkit.rb`; then one beside the file, so `plugin/context.rb` picks `spec/samagotchi/plugin/*context*` before
|
|
483
485
|
`spec/guardrails/context_spec.rb`), then the specs that name a method the change touches (the innermost `def` around a
|
|
484
486
|
changed line, read with Prism; one `git grep` for up to 12 names; names under 4 characters, `initialize`, `to_s`,
|
data/lib/samagotchi/bridge.rb
CHANGED
|
@@ -1177,11 +1177,11 @@ module Samagotchi
|
|
|
1177
1177
|
raise IntakeClosed if stopped?
|
|
1178
1178
|
next :expired if expired?("exit_expired", deadline, sid: session_id, client_id: client_id)
|
|
1179
1179
|
|
|
1180
|
-
|
|
1180
|
+
accepted = @on_exit_request.call(client_id, **options)
|
|
1181
1181
|
# Read here, right after the accept: every accept runs with the log
|
|
1182
1182
|
# held, so no later exit's list can be the one this 200 carries.
|
|
1183
|
-
stopped = @exit_stopped&.call if
|
|
1184
|
-
next
|
|
1183
|
+
stopped = @exit_stopped&.call if accepted.nil? && !restart
|
|
1184
|
+
next accepted
|
|
1185
1185
|
end
|
|
1186
1186
|
return deadline_passed("exit request") if hold == :expired
|
|
1187
1187
|
|
|
@@ -147,7 +147,7 @@ module Samagotchi
|
|
|
147
147
|
end
|
|
148
148
|
|
|
149
149
|
# A source with hooks/*.rb (listed or not) can't be installed: the run
|
|
150
|
-
# stops there, as after a manifest error (
|
|
150
|
+
# stops there, as after a manifest error (Manifest::HooksRetired.refuse_source_files).
|
|
151
151
|
def hooks_retired?
|
|
152
152
|
files = MemoryBundle::Manifest::HooksRetired.files_in(@dir)
|
|
153
153
|
return false if files.empty?
|
data/lib/samagotchi/compat.rb
CHANGED
|
@@ -18,7 +18,7 @@ module Samagotchi
|
|
|
18
18
|
MIN_AGE_DAYS = 14
|
|
19
19
|
|
|
20
20
|
SHIMS = [
|
|
21
|
-
Shim.new(id: :cards_v1_seed, added_in: "0.151.0", added_on: "2026-11-05", remove_after: "0.
|
|
21
|
+
Shim.new(id: :cards_v1_seed, added_in: "0.151.0", added_on: "2026-11-05", remove_after: "0.178.0",
|
|
22
22
|
files: ["lib/samagotchi/bridge/card_store.rb"],
|
|
23
23
|
what: "CardStore#seed_v1 reads a cards.json from before the turn log; its comment says a retention " \
|
|
24
24
|
"period after the release that wrote version 2 (0.151.0, 2026-11-05)"),
|
|
@@ -81,6 +81,16 @@ module Samagotchi
|
|
|
81
81
|
end
|
|
82
82
|
private :record_prompt_notes
|
|
83
83
|
|
|
84
|
+
# Records +parts+ (PromptPart) on the session as the sizes of the
|
|
85
|
+
# prompt's parts; saved with it. A switch records [] (the old model's
|
|
86
|
+
# parts are not the new one's; the next build records its own; a build
|
|
87
|
+
# in flight on another thread may still record the old ones, as
|
|
88
|
+
# prompt_notes may).
|
|
89
|
+
def record_prompt_parts(parts)
|
|
90
|
+
@session.prompt_parts = Array(parts) if @session
|
|
91
|
+
end
|
|
92
|
+
private :record_prompt_parts
|
|
93
|
+
|
|
84
94
|
# A failed turn's one line (the error's #summary). A host's failure
|
|
85
95
|
# under an alias says what the alias became (HostRegistry#alias_note):
|
|
86
96
|
# "host main" alone doesn't tell --model splash's user it was splash.
|
|
@@ -174,6 +184,7 @@ module Samagotchi
|
|
|
174
184
|
# The notes the new model's prompt loads at its next build, so /model,
|
|
175
185
|
# /stats and the web name them before the next turn does.
|
|
176
186
|
record_prompt_notes(model_notes) if @session
|
|
187
|
+
record_prompt_parts([])
|
|
177
188
|
sync_kernel_client!
|
|
178
189
|
@client.invalidate_context_window!
|
|
179
190
|
@metrics.forget_model_reports!
|
|
@@ -22,6 +22,20 @@ module Samagotchi
|
|
|
22
22
|
@muted_memory_names.dup
|
|
23
23
|
end
|
|
24
24
|
|
|
25
|
+
# @return [Array<String>] sorted, deduped names the prompt carries or
|
|
26
|
+
# will carry on a fresh session
|
|
27
|
+
def prompt_memory_names
|
|
28
|
+
names = Array(@prompt_builder.prompt_memory_names) + Array(prompt_notes).map(&:name)
|
|
29
|
+
names.map { |name| name.to_s.strip }.reject(&:empty?).uniq.sort
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
# @return [Array<Array(String, String, nil)>] prompt memory names and scopes
|
|
33
|
+
def prompt_memories
|
|
34
|
+
memories = Array(@prompt_builder.prompt_memories) + Array(prompt_notes).map { |note| [note.name, note.scope] }
|
|
35
|
+
memories.map { |name, scope| [name.to_s.strip, scope] }.reject { |name, _| name.empty? }.uniq
|
|
36
|
+
.sort_by { |name, scope| [name, scope.to_s] }
|
|
37
|
+
end
|
|
38
|
+
|
|
25
39
|
# @return [Array<String>] the names the session preloads (config baseline
|
|
26
40
|
# + --memory, minus mutes), known before the prompt is built, unlike
|
|
27
41
|
# #activated_memory_names
|
|
@@ -72,6 +86,8 @@ module Samagotchi
|
|
|
72
86
|
@metrics.memory_index = @prompt_builder.memory_index
|
|
73
87
|
# The model notes it carries: the session records them (/stats, /model, the web).
|
|
74
88
|
record_prompt_notes(@prompt_builder.prompt_notes)
|
|
89
|
+
# And the sizes of its parts (PromptPart), for the web's head view.
|
|
90
|
+
record_prompt_parts(@prompt_builder.prompt_parts)
|
|
75
91
|
prompt
|
|
76
92
|
end
|
|
77
93
|
|
data/lib/samagotchi/engine.rb
CHANGED
|
@@ -95,6 +95,7 @@ require_relative "model_binding"
|
|
|
95
95
|
require_relative "model_overlay"
|
|
96
96
|
require_relative "model_notes"
|
|
97
97
|
require_relative "prompt_note"
|
|
98
|
+
require_relative "prompt_part"
|
|
98
99
|
require_relative "served_model"
|
|
99
100
|
require_relative "image_store"
|
|
100
101
|
require_relative "vision_context"
|
|
@@ -124,6 +124,8 @@ module Samagotchi
|
|
|
124
124
|
# :used_memory_names [Array<String>] deduped memory names active this session
|
|
125
125
|
# :prompt_notes [Array<Hash>] the model notes the prompt carried
|
|
126
126
|
# ({name:, scope:, chars:, digest:}; #prompt_notes)
|
|
127
|
+
# :prompt_parts [Array<Hash>] the sizes of the prompt's parts
|
|
128
|
+
# ({kind:, label:, chars:, tokens:, ref:, scope:?}; Session#prompt_parts)
|
|
127
129
|
# :parent_id [String, nil] the session that delegated this one
|
|
128
130
|
# :model_name [String] the model turns run on now (after /model)
|
|
129
131
|
# :served_model, :served_model_for [String, nil] what a generation of
|
|
@@ -153,6 +155,7 @@ module Samagotchi
|
|
|
153
155
|
preloaded_memory_names: preloaded_memory_names,
|
|
154
156
|
muted_memory_names: muted.dup,
|
|
155
157
|
prompt_notes: prompt_notes.map(&:to_h),
|
|
158
|
+
prompt_parts: Array(session&.prompt_parts).map(&:to_h),
|
|
156
159
|
parent_id: session&.parent_id,
|
|
157
160
|
title: session&.title,
|
|
158
161
|
model_name: effective_model_ref,
|
|
@@ -203,7 +203,7 @@ module Samagotchi
|
|
|
203
203
|
return skip(row, "needs chi #{manifest.requires_chi}", keep_to: true)
|
|
204
204
|
end
|
|
205
205
|
|
|
206
|
-
# The upgrade would refuse it (
|
|
206
|
+
# The upgrade would refuse it (Manifest::HooksRetired.refuse_source_files).
|
|
207
207
|
hooks = Manifest::HooksRetired.files_in(row.source_dir)
|
|
208
208
|
return skip(row, Manifest::HooksRetired.for_files(hooks).message, keep_to: true) unless hooks.empty?
|
|
209
209
|
return skip(row, "project scope: chi bundle upgrade #{ship.source} in the project") if row.scope == "project"
|
|
@@ -48,16 +48,21 @@ module Samagotchi
|
|
|
48
48
|
# resolved already (SessionInbox::Head.resolve(:note, id)): no second walk
|
|
49
49
|
# @return [Result]
|
|
50
50
|
# @raise [SessionInbox::NoteRejected] an empty note or one over 16 KiB
|
|
51
|
-
# @raise [Session::NotFound] no such session
|
|
51
|
+
# @raise [Session::NotFound] no such session, or one being deleted
|
|
52
52
|
def deliver(id, text:, source:, state_dir:, from_session: nil, from_cwd: nil, objectives: nil, pin: false,
|
|
53
53
|
resolved: nil)
|
|
54
54
|
body = SessionInbox.checked_text(text)
|
|
55
|
+
path = nil
|
|
55
56
|
delivered = SessionInbox.deliver(:note, id, state_dir: state_dir, pin: pin, resolved: resolved) do |at|
|
|
56
|
-
SessionInbox.write_note(at, text: body, source: source, from_session: from_session, from_cwd: from_cwd,
|
|
57
|
-
|
|
57
|
+
path = SessionInbox.write_note(at, text: body, source: source, from_session: from_session, from_cwd: from_cwd,
|
|
58
|
+
objectives: objectives, state_dir: state_dir)
|
|
58
59
|
false
|
|
59
60
|
end
|
|
60
|
-
|
|
61
|
+
# A session being deleted is a gone one; a delete that took its lock
|
|
62
|
+
# after the write gets the note back (unless a worker read it already).
|
|
63
|
+
raise Session::NotFound, id if delivered.wake == :gone ||
|
|
64
|
+
(delivered.wake == :deleting &&
|
|
65
|
+
(path.nil? || SessionInbox.withdraw(path, delivered.id, state_dir: state_dir)))
|
|
61
66
|
|
|
62
67
|
Result.new(id: delivered.id, asked: delivered.asked, status: delivered.status, queued: delivered.queued || 0,
|
|
63
68
|
scratch: delivered.refused? && delivered.wake == :scratch)
|
|
@@ -99,7 +99,8 @@ module Samagotchi
|
|
|
99
99
|
# @return [String] the id of the session it went to
|
|
100
100
|
# @raise [Error] no such session, a one-shot owns it, it wasn't taken
|
|
101
101
|
# (a worker older than queueing refuses a queue; a stopped or
|
|
102
|
-
# archived session: session_stopped / session_archived
|
|
102
|
+
# archived session: session_stopped / session_archived; one being
|
|
103
|
+
# deleted: session_deleting), or delivery is
|
|
103
104
|
# :cut or unknown
|
|
104
105
|
def send(id, text, delivery: nil)
|
|
105
106
|
raise Error, "nothing to send" if text.to_s.strip.empty?
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative "token_usage"
|
|
4
|
+
|
|
5
|
+
module Samagotchi
|
|
6
|
+
# One part of a session's system prompt, as its size: what the session
|
|
7
|
+
# file's `prompt_parts` records at each prompt build and the web's head view
|
|
8
|
+
# draws (the text itself is not kept). kind: a SystemPrompt::KINDS word, or
|
|
9
|
+
# "tools" (the tool declarations, wherever the model gets them); label: what
|
|
10
|
+
# the row says ("AGENTS.md", "N declared"); chars: the part's length in the
|
|
11
|
+
# prompt (a multi-item section's headings and joins are in its first part,
|
|
12
|
+
# so a section's parts sum to its text); tokens: chars at TokenUsage's one
|
|
13
|
+
# ratio; ref: the bare memory name (identity, notes, preloads), the file
|
|
14
|
+
# path (agents, appended), "bundle/name" (plugins), the scope (indexes),
|
|
15
|
+
# else nil; scope: a memory part's scope, "project" or "system" (identity:
|
|
16
|
+
# system; a note: its own; a preload: the scope that answered), so the
|
|
17
|
+
# page tells a project x from a system x; nil for other kinds and in a
|
|
18
|
+
# file written before it (the page then matches by name alone).
|
|
19
|
+
PromptPart = Data.define(:kind, :label, :chars, :tokens, :ref, :scope) do
|
|
20
|
+
def initialize(kind:, label:, chars:, tokens:, ref: nil, scope: nil)
|
|
21
|
+
super
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
# A part of +chars+ characters, its tokens counted by the one ratio.
|
|
25
|
+
def self.build(kind:, label:, chars:, ref: nil, scope: nil)
|
|
26
|
+
new(kind: kind.to_s, label: label.to_s, chars: chars, tokens: tokens_for(chars), ref: ref&.to_s, scope: scope&.to_s)
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
# @return [Integer] the tokens +chars+ characters count as
|
|
30
|
+
def self.tokens_for(chars) = (chars / TokenUsage::CHARS_PER_TOKEN).ceil
|
|
31
|
+
|
|
32
|
+
# A saved or wire record (string or symbol keys); nil without a kind.
|
|
33
|
+
def self.from_h(raw)
|
|
34
|
+
return raw if raw.is_a?(PromptPart)
|
|
35
|
+
return nil unless raw.is_a?(Hash)
|
|
36
|
+
|
|
37
|
+
get = ->(key) { raw.key?(key.to_s) ? raw[key.to_s] : raw[key] }
|
|
38
|
+
kind = get.call(:kind).to_s.strip
|
|
39
|
+
return nil if kind.empty?
|
|
40
|
+
|
|
41
|
+
chars = get.call(:chars)
|
|
42
|
+
chars = chars.is_a?(Numeric) ? chars.to_i : 0
|
|
43
|
+
tokens = get.call(:tokens)
|
|
44
|
+
new(kind: kind, label: get.call(:label).to_s, chars: chars,
|
|
45
|
+
tokens: tokens.is_a?(Numeric) ? tokens.to_i : tokens_for(chars), ref: get.call(:ref)&.to_s,
|
|
46
|
+
scope: get.call(:scope)&.to_s)
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
# The records of a saved list (others dropped).
|
|
50
|
+
# @return [Array<PromptPart>]
|
|
51
|
+
def self.list(raw)
|
|
52
|
+
Array(raw).filter_map { |entry| from_h(entry) }
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
# The record (the wire's, the file's): without scope when it has none,
|
|
56
|
+
# so a part that has no scope reads as an older chi wrote it.
|
|
57
|
+
def to_h
|
|
58
|
+
hash = super
|
|
59
|
+
hash.delete(:scope) if scope.nil?
|
|
60
|
+
hash
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
# The session file's record (string keys).
|
|
64
|
+
def to_file = to_h.transform_keys(&:to_s)
|
|
65
|
+
end
|
|
66
|
+
end
|
data/lib/samagotchi/schedules.rb
CHANGED
|
@@ -1002,7 +1002,9 @@ module Samagotchi
|
|
|
1002
1002
|
# an open session is fine, so same mode does not count streams.
|
|
1003
1003
|
return [:skip, "a terminal or a web tab is open on it"] if entry.mode == CHAIN && activity[:open_streams].to_i.positive?
|
|
1004
1004
|
|
|
1005
|
-
|
|
1005
|
+
# An idle live worker: free, whatever a starting marker its own
|
|
1006
|
+
# start left (Worker#start clears it just after the lock).
|
|
1007
|
+
return nil
|
|
1006
1008
|
end
|
|
1007
1009
|
# A worker being started for it holds no lock yet (another ticker's
|
|
1008
1010
|
# firing just continued the chain to it, a resume): a chain firing
|