samagotchi 0.177.1 → 0.179.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 +4 -4
- data/CHANGELOG.md +54 -1
- data/docs/architecture.md +4 -2
- data/docs/bundles.md +16 -7
- data/docs/cli.md +30 -6
- data/docs/context.md +25 -1
- data/docs/guardrails.md +3 -2
- data/docs/internals/attached-context.md +26 -4
- data/docs/internals/background-tasks.md +26 -2
- data/docs/internals/block-renderers.md +2 -2
- data/docs/internals/bridge.md +28 -8
- data/docs/internals/bundles.md +63 -34
- data/docs/internals/engine.md +1 -1
- data/docs/internals/remote-sessions.md +6 -1
- data/docs/internals/session-lifecycle.md +17 -8
- data/docs/internals/web-frontend.md +25 -4
- data/docs/internals/working-set.md +31 -5
- data/docs/plugins.md +14 -3
- data/docs/releasing.md +3 -3
- data/docs/scheduling.md +12 -1
- data/docs/sessions.md +16 -6
- data/docs/testing.md +4 -1
- data/lib/samagotchi/block_renderers.rb +12 -14
- data/lib/samagotchi/bootstrap/bundles.rb +2 -2
- data/lib/samagotchi/bootstrap_command.rb +1 -1
- data/lib/samagotchi/bridge/card_store.rb +2 -19
- data/lib/samagotchi/bridge/card_wait.rb +34 -0
- data/lib/samagotchi/bridge/turn_accumulator.rb +22 -4
- data/lib/samagotchi/bridge.rb +38 -6
- data/lib/samagotchi/bundle_command/check.rb +10 -10
- data/lib/samagotchi/bundle_command/installed_check.rb +2 -2
- data/lib/samagotchi/bundle_command/try/sandbox.rb +3 -3
- data/lib/samagotchi/bundle_command.rb +17 -17
- data/lib/samagotchi/bundle_manifest.rb +579 -0
- data/lib/samagotchi/bundle_needs.rb +9 -8
- data/lib/samagotchi/bundle_settings_check.rb +9 -8
- data/lib/samagotchi/bundles/claude-peer/manifest.yml +5 -3
- data/lib/samagotchi/bundles/claude-peer/plugin.rb +4 -4
- data/lib/samagotchi/bundles/claude-peer/scripts/chi-peer-SKILL.md +11 -6
- data/lib/samagotchi/bundles/codex-peer/manifest.yml +5 -3
- data/lib/samagotchi/bundles/codex-peer/plugin.rb +4 -3
- data/lib/samagotchi/bundles/codex-peer/scripts/chi-peer-SKILL.md +11 -6
- data/lib/samagotchi/bundles/system/manifest.yml +2 -2
- data/lib/samagotchi/bundles/system/memory_guide.md +1 -1
- data/lib/samagotchi/compat.rb +0 -7
- data/lib/samagotchi/config.rb +2 -2
- data/lib/samagotchi/context_absorber.rb +36 -6
- data/lib/samagotchi/context_note.rb +8 -5
- data/lib/samagotchi/context_providers.rb +30 -27
- data/lib/samagotchi/context_sources.rb +42 -12
- data/lib/samagotchi/engine/events.rb +43 -0
- data/lib/samagotchi/engine/messages.rb +1 -1
- data/lib/samagotchi/engine.rb +9 -3
- data/lib/samagotchi/event_fanout.rb +56 -0
- data/lib/samagotchi/events.rb +6 -5
- data/lib/samagotchi/guardrail_wiring.rb +20 -21
- data/lib/samagotchi/guardrails/approval.rb +3 -2
- data/lib/samagotchi/guardrails/approvals.rb +0 -4
- data/lib/samagotchi/guardrails/outside.rb +3 -3
- data/lib/samagotchi/{memory_bundle → installed_bundles}/bundle_hook.rb +1 -1
- data/lib/samagotchi/installed_bundles/dir.rb +129 -0
- data/lib/samagotchi/{memory_bundle → installed_bundles}/file_digest.rb +1 -1
- data/lib/samagotchi/{memory_bundle → installed_bundles}/file_standing.rb +2 -2
- data/lib/samagotchi/{memory_bundle/installed_manifest.rb → installed_bundles/manifest.rb} +21 -21
- data/lib/samagotchi/{memory_bundle → installed_bundles}/plugin_ref.rb +2 -2
- data/lib/samagotchi/{memory_bundle/installed_bundle.rb → installed_bundles/record.rb} +17 -17
- data/lib/samagotchi/installed_bundles/sha.rb +41 -0
- data/lib/samagotchi/installed_bundles/standing.rb +45 -0
- data/lib/samagotchi/installed_bundles.rb +90 -0
- data/lib/samagotchi/memory_bundle/asset_installer.rb +7 -7
- data/lib/samagotchi/memory_bundle/builder.rb +13 -13
- data/lib/samagotchi/memory_bundle/file_state.rb +9 -9
- data/lib/samagotchi/memory_bundle/installed_copy.rb +6 -6
- data/lib/samagotchi/memory_bundle/installer.rb +33 -33
- data/lib/samagotchi/memory_bundle/listing.rb +5 -5
- data/lib/samagotchi/memory_bundle/manifest_standing.rb +7 -7
- data/lib/samagotchi/memory_bundle/merger.rb +15 -15
- data/lib/samagotchi/memory_bundle/profile.rb +8 -8
- data/lib/samagotchi/memory_bundle/provenance.rb +59 -192
- data/lib/samagotchi/memory_bundle/remerge.rb +16 -16
- data/lib/samagotchi/memory_bundle/shas.rb +2 -2
- data/lib/samagotchi/memory_bundle/shipped_history.rb +1 -1
- data/lib/samagotchi/memory_bundle/shipped_update.rb +17 -17
- data/lib/samagotchi/memory_bundle/status.rb +15 -15
- data/lib/samagotchi/memory_bundle/system_bundle.rb +12 -12
- data/lib/samagotchi/memory_bundle/trash.rb +2 -2
- data/lib/samagotchi/memory_bundle/uninstaller.rb +8 -8
- data/lib/samagotchi/memory_bundle.rb +2 -2
- data/lib/samagotchi/memory_command.rb +4 -4
- data/lib/samagotchi/{memory_bundle → memory_index}/entry_size.rb +8 -8
- data/lib/samagotchi/{memory_bundle/index_size.rb → memory_index/size.rb} +6 -6
- data/lib/samagotchi/{memory_bundle/index_sync.rb → memory_index/sync.rb} +5 -5
- data/lib/samagotchi/{memory_bundle/index_updater.rb → memory_index/updater.rb} +2 -2
- data/lib/samagotchi/memory_usage.rb +5 -5
- data/lib/samagotchi/muted_memories.rb +1 -1
- data/lib/samagotchi/peer_exchanges.rb +76 -0
- data/lib/samagotchi/plugin/context.rb +4 -0
- data/lib/samagotchi/plugin/loader.rb +35 -33
- data/lib/samagotchi/plugin/peer.rb +42 -11
- data/lib/samagotchi/project_subfolders.rb +9 -9
- data/lib/samagotchi/reply_wait/target.rb +11 -4
- data/lib/samagotchi/schedules.rb +9 -4
- data/lib/samagotchi/self_report.rb +14 -14
- data/lib/samagotchi/session_access/contract.rb +4 -0
- data/lib/samagotchi/session_access/local.rb +32 -5
- data/lib/samagotchi/session_access/remote.rb +44 -10
- data/lib/samagotchi/session_archive_command.rb +38 -10
- data/lib/samagotchi/session_chain/delete.rb +75 -25
- data/lib/samagotchi/session_config.rb +23 -19
- data/lib/samagotchi/session_delete_command.rb +33 -10
- data/lib/samagotchi/session_lifecycle/allowed.rb +12 -9
- data/lib/samagotchi/session_manager/lifecycle.rb +12 -26
- data/lib/samagotchi/session_manager/removal.rb +109 -25
- data/lib/samagotchi/session_manager/running_tasks.rb +347 -0
- data/lib/samagotchi/session_retention.rb +13 -4
- data/lib/samagotchi/session_stores.rb +3 -0
- data/lib/samagotchi/sessions_command.rb +1 -1
- data/lib/samagotchi/system_prompt.rb +4 -4
- data/lib/samagotchi/task_files.rb +37 -4
- data/lib/samagotchi/terminal_ui/attach_launcher.rb +5 -1
- data/lib/samagotchi/terminal_ui/attached_loop/exit_commands.rb +7 -1
- data/lib/samagotchi/terminal_ui/attached_loop.rb +1 -1
- data/lib/samagotchi/terminal_ui/formatting.rb +2 -2
- data/lib/samagotchi/terminal_ui/local_link.rb +11 -3
- data/lib/samagotchi/terminal_ui/model_segments_text.rb +5 -5
- data/lib/samagotchi/terminal_ui.rb +4 -1
- data/lib/samagotchi/testing/bundle.rb +3 -3
- data/lib/samagotchi/testing/install.rb +3 -3
- data/lib/samagotchi/testing/sandbox.rb +2 -2
- data/lib/samagotchi/tool_runner.rb +14 -14
- data/lib/samagotchi/tools/memory.rb +22 -22
- data/lib/samagotchi/tools/task_runtime.rb +25 -6
- data/lib/samagotchi/update_command.rb +4 -4
- data/lib/samagotchi/version.rb +1 -1
- data/lib/samagotchi/web/app.rb +19 -2
- data/lib/samagotchi/web/message_display.rb +6 -0
- data/lib/samagotchi/web/participant_view.rb +1 -1
- data/lib/samagotchi/web/proxy_gate.rb +1 -0
- data/lib/samagotchi/web/public/card_kinds.js +8 -3
- data/lib/samagotchi/web/public/cards_place.js +15 -1
- data/lib/samagotchi/web/public/ctx.js +1 -1
- data/lib/samagotchi/web/public/data.js +19 -7
- data/lib/samagotchi/web/public/delete_sheet.js +26 -7
- data/lib/samagotchi/web/public/history_shape.js +3 -0
- data/lib/samagotchi/web/public/running_tasks.js +73 -0
- data/lib/samagotchi/web/public/session_actions.js +57 -8
- data/lib/samagotchi/web/public/stop_sheet.js +3 -2
- data/lib/samagotchi/web/public/turn_block.js +46 -8
- data/lib/samagotchi/web/public/turn_settle.js +117 -0
- data/lib/samagotchi/web/public/working_set.js +3 -28
- data/lib/samagotchi/web/public/working_set_view.js +5 -2
- data/lib/samagotchi/web/public/ws_item_sig.js +51 -0
- data/lib/samagotchi/web/public/ws_peek.js +23 -13
- data/lib/samagotchi/web/public/ws_reader.js +22 -12
- data/lib/samagotchi/web/public/ws_timeline.js +9 -6
- data/lib/samagotchi/web/push/notifier.rb +2 -2
- data/lib/samagotchi/web/session_access_routes.rb +21 -1
- data/lib/samagotchi/web/session_control.rb +65 -16
- data/lib/samagotchi/web/session_hub.rb +20 -4
- data/lib/samagotchi/web/working_set_routes.rb +29 -8
- data/lib/samagotchi/worker_boot.rb +4 -1
- data/lib/samagotchi/worker_link.rb +9 -1
- data/lib/samagotchi/working_set.rb +26 -0
- data/lib/samagotchi/working_set_command.rb +9 -6
- metadata +22 -12
- data/lib/samagotchi/memory_bundle/manifest.rb +0 -581
data/docs/plugins.md
CHANGED
|
@@ -511,6 +511,9 @@ chi.on(:before_tool_call, priority: 10, on_error: :fail_closed) { |event, _ctx|
|
|
|
511
511
|
to load (a sha256 that differs, an unmet `requires_chi`, a raise in the file
|
|
512
512
|
or in `register`) is a **required guardrail failure**: every tool call is
|
|
513
513
|
denied until it is fixed ([guardrails.md](guardrails.md#failing-closed)).
|
|
514
|
+
If manifest.json doesn't read, chi treats the bundle as required unless the
|
|
515
|
+
kept manifest.yml reads and names no plugin or a plugin without
|
|
516
|
+
`required: true`; reinstall the bundle to fix it.
|
|
514
517
|
Without the flag a fail-closed hook still denies the call it raises on, but
|
|
515
518
|
a load failure denies nothing; `chi bundle check` warns (`fail-closed`) and
|
|
516
519
|
the log says so (`plugin_fail_closed_unrequired`).
|
|
@@ -985,7 +988,9 @@ In the web, a turn's block collapses when the turn ends. A `:warn` card, and
|
|
|
985
988
|
any card of a turn that ended without completing (cancelled, failed, the
|
|
986
989
|
worker gone), then moves out of the block, after the turn's end line, so it
|
|
987
990
|
stays in sight; a reload puts it in the same place. An `:info` card of a
|
|
988
|
-
completed turn stays in its step.
|
|
991
|
+
completed turn stays in its step. A card that asks (check-in's) sits beside the block, in the order it showed live:
|
|
992
|
+
where it stopped asking, or after the turn's answered questions when it still asked at the end; a reload puts it
|
|
993
|
+
there too.
|
|
989
994
|
|
|
990
995
|
Between turns, a card goes above the first turn prompt after it, live and
|
|
991
996
|
after a reload. A failed turn whose prompt went back to its sender isn't a
|
|
@@ -1451,7 +1456,13 @@ that calls it, or for a real external bundle that does. No method on the chance
|
|
|
1451
1456
|
`check_hint!`, `paired_lines`, `transport_line`, `peer_dir` and
|
|
1452
1457
|
`setup_paragraph` (optionally `skill_substitutions`), and sets `NAME`,
|
|
1453
1458
|
`APP`, `COMMAND`, `USAGE`, `OUTBOX` and `SCRIPTS_DIRS`. These constants are
|
|
1454
|
-
read as `self.class::X`.
|
|
1459
|
+
read as `self.class::X`. The base names each send: `Peer.send_id(kind, title, text)` (`s-` and 6 hex
|
|
1460
|
+
of SHA-256 over the args as given) is the message's second line (`ref: <id>`), the tool row's `peer` ref
|
|
1461
|
+
(display only, no actions; computed from the args before the call runs, so a send that then fails has it too)
|
|
1462
|
+
and the last send's `id`; the peer's answer echoes it as `re` ([context.md](context.md#the-command-contract)).
|
|
1463
|
+
Successful sends and transport failures are recorded in the session's peer exchange log; answer pushes add
|
|
1464
|
+
summaries, not answer texts. The log does not enter the model's context.
|
|
1465
|
+
See the [claude-peer](bundles.md#the-claude-peer-bundle) and
|
|
1455
1466
|
[codex-peer](bundles.md#the-codex-peer-bundle) bundles.
|
|
1456
1467
|
3. `Samagotchi::Tools::ToolIndex::Tool` and `Samagotchi::Tools::ToolIndex::Group`
|
|
1457
1468
|
values, `Samagotchi::Tools::ToolIndex.schema_note` and
|
|
@@ -1468,7 +1479,7 @@ that calls it, or for a real external bundle that does. No method on the chance
|
|
|
1468
1479
|
and [bundles.md](bundles.md) document them — `name`, `version`, `scope`, `description`, `files`, `hooks`,
|
|
1469
1480
|
`trust_level`, `plugin`, `requires_chi`, `requires_chi_next` (shipped bundles only: the release tooling
|
|
1470
1481
|
reads it, chi doesn't), `needs`, `scripts`, `context_providers`, `block_renderers`, `includes`,
|
|
1471
|
-
`session_settings`, `settings`. Those are `
|
|
1482
|
+
`session_settings`, `settings`. Those are `BundleManifest::KEYS`; `BundleManifest::SINCE` is the chi release each
|
|
1472
1483
|
key or shape first worked in, and the docs don't copy it — the code is its truth.
|
|
1473
1484
|
- A key keeps its meaning. A new key gets a `SINCE` entry and a CHANGELOG line, and an older chi says
|
|
1474
1485
|
it ignores it (`unknown-key`).
|
data/docs/releasing.md
CHANGED
|
@@ -32,7 +32,7 @@ can run the whole release; the user approves the notes before the tag and the
|
|
|
32
32
|
- a new `ctx.*` / `chi.*` call a plugin may make gets its release's version in `Plugin::Api::SINCE` once
|
|
33
33
|
released (`chi bundle check`'s `requires-chi-floor` reads it); an unreleased one waits there as an `# Unreleased` comment, and
|
|
34
34
|
`release:bump` moves each call it names up with the new version (`release:check` fails while a comment is left);
|
|
35
|
-
- a new manifest key or shape gets its release's version in `
|
|
35
|
+
- a new manifest key or shape gets its release's version in `BundleManifest::SINCE` the same way (check's
|
|
36
36
|
`requires-chi-floor` reads it for the manifest too), waits as an `# Unreleased` comment while unreleased,
|
|
37
37
|
and `release:bump` moves it up with the new version the same way;
|
|
38
38
|
- a new shipped bundle joins a profile (`includes:` in `core` or `dev`; a
|
|
@@ -76,8 +76,8 @@ 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, `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 `
|
|
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 `
|
|
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 `BundleManifest::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
|
+
| `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 `BundleManifest::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
|
|
|
83
83
|
## Runbook
|
data/docs/scheduling.md
CHANGED
|
@@ -107,8 +107,12 @@ time zones.
|
|
|
107
107
|
|
|
108
108
|
A cron tick cannot read a worker's memory, so the tick has two paths.
|
|
109
109
|
|
|
110
|
+
**Being deleted** (a deleter holds the owner lock) comes before a stop marker.
|
|
111
|
+
The skip is "the session is being deleted", and the next tick finds the session
|
|
112
|
+
gone.
|
|
113
|
+
|
|
110
114
|
**Stopped by its owner** (`chi sessions stop`, the web's Stop: the stop marker,
|
|
111
|
-
`WorkerPresence#stop_marked?`) comes
|
|
115
|
+
`WorkerPresence#stop_marked?`) comes next, in both modes: a skip ("the session is
|
|
112
116
|
stopped; only its owner's message starts it again"), never a restart. A stop that
|
|
113
117
|
lands between the check and a same-mode firing is the same skip: `deliver_turn`
|
|
114
118
|
refuses a schedule's wake of a stopped session (a schedule is no person,
|
|
@@ -139,6 +143,9 @@ the tick says to restart that worker.
|
|
|
139
143
|
to ask: `chi sessions restart ID`" — chi's usual rule for an older worker:
|
|
140
144
|
refuse with a restart, never silently degrade. `same` mode, which only queues a
|
|
141
145
|
turn, may use the file checks.
|
|
146
|
+
- A worker whose chi is newer than the ticker's (its Bridge speaks a newer
|
|
147
|
+
protocol) can't be asked. The skip is "its worker runs a newer chi: restart chi
|
|
148
|
+
web or update this chi", in both modes.
|
|
142
149
|
|
|
143
150
|
A `chi send --wait` or a parent's `delegate` wait is **not** busy: `ReplyWait::Poll`
|
|
144
151
|
reads the session files and `GET /session/:id/state`, never `open_stream`, so a
|
|
@@ -241,6 +248,10 @@ its descendants, and archived sessions are outside the retention sweep
|
|
|
241
248
|
count. The `anchor` is never pruned: it is the chain's root, the id the user and
|
|
242
249
|
the coordinator remember, and `last:<anchor>` must keep resolving.
|
|
243
250
|
|
|
251
|
+
Schedule prune leaves the deleted links' background tasks running: a later link
|
|
252
|
+
may still use a server started by an earlier link in the same project. Continue
|
|
253
|
+
does not yet transfer task ownership.
|
|
254
|
+
|
|
244
255
|
The oldest kept link still has `continues` naming a link that is gone. The walks
|
|
245
256
|
follow `continues` forward, so nothing breaks; the web's `↩ #N of M` chip counts
|
|
246
257
|
from the surviving root (pruning renumbers the links) and says "earlier links
|
data/docs/sessions.md
CHANGED
|
@@ -2,6 +2,10 @@
|
|
|
2
2
|
|
|
3
3
|
Sessions are plain files — no DB. Each session is `~/.local/state/samagotchi/sessions/<uuid>.json` (XDG-aware via `XDG_STATE_HOME`) plus a sidecar dir `<uuid>/` with `input/`/`notes/`/`output/`/`owner.lock`/`bridge.json` (`Session.session_dir`), `turn_drawings.jsonl` once a turn ended with a Bridge or in a one-shot run (each finished turn as live drew it, which the web's reload draws: [bridge.md](internals/bridge.md#turndrawings); a fork starts with its parent's lines for the turns its seed keeps unchanged, a continue with none: its turns, and any without a line, are drawn from their messages), and `tool_output/` once a long `execute` result was cut: its whole output, which the cut result names (`ToolOutputFiles`, the newest 50 kept; see [Tool output guardrails](internals/tool-output-limits.md#the-runners-cut-max_tool_output_chars)). Its keys are in [the Session file table](#session-file). A file from before `used_memory_names`, `preloaded_memory_names`, `muted_memory_names`, `parent_id` or `continues` reads those as empty lists, no parent and no previous link.
|
|
4
4
|
|
|
5
|
+
The sidecar's `peer_exchanges.jsonl` records peer sends, transport failures
|
|
6
|
+
and answer summaries, never answer text. It stays with the previous link on a
|
|
7
|
+
continue; the new link starts empty. See [context storage](context.md#storage).
|
|
8
|
+
|
|
5
9
|
**Message times:** an entry of `messages` may carry `at`, when it happened: a local-offset ISO time with milliseconds (`2026-10-24T14:32:05.120+02:00`). User prompts, lines merged into a turn and steers, reminders, context and task notes, and the model's replies have one (a note's is its `created_at`); tool results, `!cmd` messages and chi's own turn notes don't, nor does anything saved before chi stamped messages (no backfill). It is for the UIs only (the gap dividers, a bubble's time): it never goes to the model, so it changes nothing in the requests or their prompt cache. The one time the model reads is the reminders': due reminders go into a turn as a system message headed `[SYSTEM: REMINDERS DUE 2026-10-24 14:32 local]` (the turn's local time; `ReminderQueue#inject!`), written into the saved content then, so a later request sends the same text.
|
|
6
10
|
|
|
7
11
|
**Verify verdicts:** a web Verify turn stamps its opening user message with `verify: {turn_id, quote}` (the selected source turn and quote; metadata only, never added to the prompt). When that turn completes and the final assistant reply's last non-empty line is a valid `Verdict: confirmed|refuted|unclear — <reason>`, the session file appends `{anchor: {turn_id, quote}, verdict, reason, by, check_turn_id, at}` to its optional `verdicts` array. `by` is the turn's author (nil for the owner), `check_turn_id` names the Verify turn, and `at` is its timestamp. The array is append-only; older files without it have no saved verdicts. An `unclear` verdict can be checked again by **Verify fresh** (a delegate child that gets only the claim; see *Delegating*): its verdict is appended to the parent's `verdicts` with `fresh: true`, `of` (the verdict it checked again) and `child_id`, from the parent's `fresh_verdicts/` dir, which its worker takes between turns. Verdicts are display state: none enters a prompt.
|
|
@@ -23,6 +27,8 @@ Sessions are plain files — no DB. Each session is `~/.local/state/samagotchi/s
|
|
|
23
27
|
|
|
24
28
|
A session is deleted if **expired by age OR overflow by count** (unless `keep_status` or the live-owner guard: a session a worker or `chi` still has open is never pruned). A session's `status` is its turn state (`idle`/`running`), not whether a worker is alive. Orphan dirs without a `*.json` are never deleted, except skeleton-only ones (see *Empty sessions*). Deletion removes its `*.json` and sidecar dir under the deleting owner lock, along with its plugin state, attached context, participant grants, System 1 runs and context-candidate records. Explicit delete and retention use the same cleanup path. Set both `DAYS=0` and `MAX=0` to retain forever.
|
|
25
29
|
|
|
30
|
+
Retention and manual prune/clean silently stop each deleted session's verified background tasks under its deleting lock, with `by: retention` (`stopped_by_retention`). Sessions are processed sequentially, their tasks in parallel. Unverified or unreadable tasks are not signalled; stops and failures are logged per task as `retention_task_stopped` / `retention_task_not_stopped`, without commands. A scratch session's own cleanup does the same with `by: scratch` and `scratch_task_stopped` / `scratch_task_not_stopped`.
|
|
31
|
+
|
|
26
32
|
**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
33
|
|
|
28
34
|
**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.
|
|
@@ -41,15 +47,15 @@ A new session field is one `Session::FIELDS` row, plus a `SessionSetup` member w
|
|
|
41
47
|
|
|
42
48
|
**A worker killed mid-turn:** while a turn runs, its worker keeps it on disk (`TurnCheckpoint`): the session file has the turn so far (the prompt from the turn's start, then the finished tool steps and lines merged into it) and `interrupted_turn: {id, started_at, at, iteration, enqueued_id}` (`enqueued_id`: the input the turn runs, so any process can tell which turn is running; a continue turn carries its offer turn's), written as the turn starts, at the loop's first iteration boundary and then at most every 10 s (`updated_at` moves with it). The turn's end saves the real messages without the mark. A worker that died without ending its turn (SIGKILL, a crash of the process) leaves the mark, and loses what came after its last written boundary: at most the last 10 s of steps, plus the step in flight. Each checkpoint write also saves the turn's metrics so far to `analytics.json` (tokens, speeds, timings, its finished tool calls), as the record a killed turn leaves: canceled, `cancellation_reason: worker_stopped`; the turn's own end writes over it. The next worker to start for the session (a `chi send`, `--resume`, `--attach`, the web), or a `chi --resume ID -p TEXT --non-interactive` run, settles the turn before anything else (`TurnCheckpoint.settle`, log `interrupted_turn_settled`): a note `the previous turn was cancelled (worker-stopped) after Ns` goes at the tail, the status goes idle and the mark goes; `last_turn` stays the previous turn's (a new one saved before the turn a `chi send --wait` woke the worker for would end that wait at once); the dead turn's end is recorded under its `enqueued_id` instead, in `<id>/input/settled/<enqueued_id>` (a `last_turn` record: canceled, `cancel_reason: worker_stopped`), which only a wait for that very turn reads (`chi send --queue --wait`, a `chi send --wait -m` to an idle session or `--new`, `chi send --wait ID --turn`, a continue's wait): it ends `canceled` with `cancel_reason: worker_stopped`, detail "its worker exited mid-turn", instead of timing out. A wake or reminder turn's settle is recorded under its worker-minted `wake-…` id the same way, and a message merged into a turn as a steer follows that turn's id (`input/merged/`). A wait with no turn id that saw the turn running ends the same way when the settle comes (`chi send --wait ID` with no message on a turn with no id, such as a 0.156 worker's reminder turn), unless an input still waits or was claimed since: an unmerged message runs as its own turn next, and that turn's end is the answer. A reply the turn wrote before its worker died is still its answer. The session shows the turn's prompt and steps with that note; the dead turn is not run again, and the model reads on its next turn that it was cut.
|
|
43
49
|
|
|
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.
|
|
50
|
+
**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 delete or an archive differs: it never leaves a task the session started running unasked (*Deleting a session*: refused, or `--stop-tasks` stops it), where Stop's "Stop session only" does. 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
51
|
|
|
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`).
|
|
52
|
+
**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`). **Background tasks still running:** a user's delete (these three, and `chi sessions delete`) asks first when tasks the deleted sessions started (their `task_create` tasks and the `execute` runs handed over at their limit, read from each session's transcript and `<working_directory>/tmp/tasks/<id>/task.json`: `SessionManager::RunningTasks`) still run: it is refused before anything changes (`tasks_running`), and the CLI's `--stop-tasks`, the web's `stop_tasks=true` (the delete's and the chain delete's query) stop them first (`stopped_by_user`, TERM then KILL after 3 s, all at once, about 4 s at most), under the deleting lock, after the starting-marker re-check, so no worker takes the session meanwhile; that last check refuses a task that started since the first (`worker_stopped: true` when the worker was stopped by then). One rule, fail-safe: a task whose pid still leads the group chi started at the start time it recorded is *running*; one whose record has no start time (before 2026-10-09) or whose start time reads nothing now, while its pid leads a group, is *unverified* ("may still be running"); a `task.json` that doesn't read is *unreadable*. All three refuse; a stop signals only the running ones (an unverified pid may belong to another process now) and reports the rest as not stopped, then deletes. A record left marked running whose pid is gone (a crashed worker's) isn't listed. The 409 is `{error: "tasks_running", reason, op: "delete", detail, session_id, tasks: {running, unverified, unreadable}, worker_stopped, stopped_worker}` (`stopped_worker`: whose worker the delete stopped before the last check refused), each task `{session_id, id, command}` (`links` too for a chain delete's other links); the 200 gains `tasks_stopped`, `tasks_not_stopped` and `tasks_ended` (empty unless stopped). A session's file gone (its folder left) has no tasks. The retention sweep and scratch cleanup stop verified tasks silently; the empty-session discard, failed-continue rollback and schedule prune leave them running.
|
|
47
53
|
|
|
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.
|
|
54
|
+
<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. **Background tasks still running** in the session or a delegate refuse an archive as they refuse a delete (*Deleting a session*: the same rule and listing), before anything changes: 409 `tasks_running` (not `busy`, so an older client doesn't say "a turn is running"), `op: "archive"`. `chi sessions archive --stop-tasks`, or the archive route's body `{"stop_tasks": true}`, stops them first: after the tree's live workers were stopped and let go (or the wait ran out: such a worker's own waiter then records the stop from the `stop_requested_by` flag on disk), and before the marker; the 200 gains `tasks_stopped`, `tasks_not_stopped` and `tasks_ended`. An archive takes no lock for it. Undo (unarchive) doesn't restart them. 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
55
|
|
|
50
56
|
**System 1's saved runs** last as long as sessions: the sweep ages them by day file, and deleting a session purges its runs ([system-one.md](system-one.md)).
|
|
51
57
|
|
|
52
|
-
**Lazy sweep:** automatic prune runs only while `chi web` runs, at most once per `session.sweep_interval_hours` (default 24): the web's session hub gives it a chance on its periodic full scan, and `GET /api/sessions` does too. No cron, and a terminal-only chi never sweeps. Manual prune is always available.
|
|
58
|
+
**Lazy sweep:** automatic prune runs only while `chi web` runs, at most once per `session.sweep_interval_hours` (default 24): the web's session hub gives it a chance on its periodic full scan, and `GET /api/sessions` does too. It runs on one background thread outside the hub's session list lock, so task stops don't block the list. No cron, and a terminal-only chi never sweeps. Manual prune is always available.
|
|
53
59
|
|
|
54
60
|
<a id="cli"></a>**CLI:**
|
|
55
61
|
|
|
@@ -551,12 +557,16 @@ leave) for the owner lock, and resumes the session; a worker that doesn't let
|
|
|
551
557
|
go in time is reported as "didn't take the restart" and nothing is resumed. A
|
|
552
558
|
worker that took the lock meanwhile (the old one handed over after all) is
|
|
553
559
|
not touched. It refuses first if disk shows a running turn, pending
|
|
554
|
-
question or approval, queued input, or a
|
|
555
|
-
|
|
560
|
+
question or approval, queued input, or a background task started by the
|
|
561
|
+
session that may still run (`SessionManager::RunningTasks`, as a delete reads
|
|
562
|
+
it: a live one, one it can't verify, an unreadable record; a record left
|
|
563
|
+
marked running whose pid is gone doesn't hold it); the message directs the
|
|
564
|
+
user to `chi sessions stop ID`, then any prompt.
|
|
556
565
|
Reminders, a running `/btw`, and other in-memory worker state cannot be
|
|
557
566
|
checked and may be lost in this fallback. A stopped worker (SIGSTOP or
|
|
558
567
|
Ctrl-Z: `ps` state `T`) answers neither the ask nor a TERM, so a restart
|
|
559
568
|
refuses it at once, before asking, with its pid and `kill -CONT PID`. A
|
|
560
569
|
session whose stop is marked (stopped, or its worker being stopped) is refused
|
|
561
570
|
before any of this (`stop_marked`: no successor would come).
|
|
571
|
+
A session being deleted is refused the same way (`deleting`).
|
|
562
572
|
The web restart route behaves the same way.
|
data/docs/testing.md
CHANGED
|
@@ -284,7 +284,9 @@ run, CI) and too long on a fast one. The contract a new spec follows:
|
|
|
284
284
|
twice for it: a second boundary crossed between the reads moves the edge (`ModelProfile.model_warning(now:)`).
|
|
285
285
|
3. **What a spec starts, it stops and waits for** before teardown: `join!(thread, what)`, `with_task_dir { … }`
|
|
286
286
|
(spec/support/task_dirs.rb: a tasks' folder of its own, its tasks stopped and their exit-status recorders joined
|
|
287
|
-
with `TaskRuntime.quiesce!`), a `stop` that joins (`IdleScheduler#stop`)
|
|
287
|
+
with `TaskRuntime.quiesce!`), a `stop` that joins (`IdleScheduler#stop`), `stop_session_hubs` before removing a
|
|
288
|
+
`Web::SessionHub`'s state dir (spec/support/session_hubs.rb: its retention sweep thread writes there). Never only
|
|
289
|
+
`Thread#kill`.
|
|
288
290
|
4. **"Nothing happens" is shown by counting passes** (the worker's loop rounds, spec/support/worker_loop_rounds.rb;
|
|
289
291
|
a class's ticks), not by a pause.
|
|
290
292
|
5. **A wall-clock bound** only as "not the full N s", with at least 5× headroom measured on the slow (x86) laptop.
|
|
@@ -399,6 +401,7 @@ any other file requires it, so a spec file run alone still finds its requires. E
|
|
|
399
401
|
| `recording_surface.rb` | `RecordingSurface`: a `TerminalUI::Surface` that records commits and slots instead of drawing |
|
|
400
402
|
| `remote_backend.rb` | `RemoteBackend`: `SessionAccess::Remote` against chi web's Rack app in this process (no socket, LAN token gate) |
|
|
401
403
|
| `reply_wait_looks.rb` | `ReplyWaitLooks`: counts a `ReplyWait`'s polls, so a step waits for the looks instead of a delay |
|
|
404
|
+
| `session_hubs.rb` | `stop_session_hubs`: stops every `Web::SessionHub` the example built (joining its sweep thread) before a teardown removes the state dir; a config-level after stops any left over |
|
|
402
405
|
| `stamps.rb` | *helper*: `next_stamp`, distinct ordered times for the lib's `now:` seams; the pinned history clock |
|
|
403
406
|
| `task_dirs.rb` | `with_task_dir`: a tasks' folder of its own, every task stopped and its recorders joined after |
|
|
404
407
|
| `test_kernel.rb` | `TestKernel`: `test_kernel` (a real `KernelLoop` to stub `#run` on; its options are `KernelLoop::Services` fields), `attach_services` (swap some of a kernel's services), `run_context` and `test_client` for Engine specs |
|
|
@@ -1,13 +1,11 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
|
+
require_relative "installed_bundles"
|
|
4
|
+
|
|
3
5
|
module Samagotchi
|
|
6
|
+
autoload :BundleManifest, File.expand_path("bundle_manifest", __dir__)
|
|
4
7
|
autoload :InlineWidgets, File.expand_path("inline_widgets", __dir__)
|
|
5
8
|
autoload :Log, File.expand_path("log", __dir__)
|
|
6
|
-
autoload :VERSION, File.expand_path("version", __dir__)
|
|
7
|
-
module MemoryBundle
|
|
8
|
-
autoload :Manifest, File.expand_path("memory_bundle/manifest", __dir__)
|
|
9
|
-
autoload :Provenance, File.expand_path("memory_bundle/provenance", __dir__)
|
|
10
|
-
end
|
|
11
9
|
|
|
12
10
|
# Declarative block renderers (docs/plugins.md, docs/internals/block-renderers.md):
|
|
13
11
|
# a bundle's manifest maps a fenced block's language to the scripts/ files the
|
|
@@ -70,7 +68,7 @@ module Samagotchi
|
|
|
70
68
|
raise Invalid, "block_renderers: #{lang} is drawn by chi itself; a bundle can't render it" if RESERVED.include?(lang)
|
|
71
69
|
|
|
72
70
|
load = data["load"]
|
|
73
|
-
unless load.is_a?(Array) && !load.empty? && load.all? { |file| file.is_a?(String) && file.match?(
|
|
71
|
+
unless load.is_a?(Array) && !load.empty? && load.all? { |file| file.is_a?(String) && file.match?(BundleManifest::SCRIPT_FILE) }
|
|
74
72
|
raise Invalid, "block_renderers: #{lang}'s load must be a non-empty list of file names in scripts/, not #{load.inspect}"
|
|
75
73
|
end
|
|
76
74
|
|
|
@@ -83,11 +81,11 @@ module Samagotchi
|
|
|
83
81
|
# @return [Array<Installed>]
|
|
84
82
|
def for_installed
|
|
85
83
|
taken = {}
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
next if manifest.requires_chi_failure(VERSION)
|
|
84
|
+
InstalledBundles.standings do |standing|
|
|
85
|
+
next if standing.too_new?
|
|
89
86
|
|
|
90
|
-
|
|
87
|
+
bundle = standing.name
|
|
88
|
+
renderers(bundle, standing.record.manifest).each do |renderer|
|
|
91
89
|
taken[renderer.lang] ||= Installed.new(lang: renderer.lang, bundle: bundle, files: renderer.load)
|
|
92
90
|
end
|
|
93
91
|
end
|
|
@@ -104,11 +102,11 @@ module Samagotchi
|
|
|
104
102
|
def script_path(bundle, file)
|
|
105
103
|
return nil unless for_installed.any? { |renderer| renderer.bundle == bundle && renderer.files.include?(file) }
|
|
106
104
|
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
raise Invalid,
|
|
105
|
+
installed = InstalledBundles::Dir.new(name: bundle)
|
|
106
|
+
refusal = installed.file_refusal(:scripts, file, InstalledBundles.standing(bundle)&.record&.scripts&.fetch(file, nil))
|
|
107
|
+
raise Invalid, refusal.text if refusal
|
|
110
108
|
|
|
111
|
-
File.join(
|
|
109
|
+
File.join(installed.scripts_dir, file)
|
|
112
110
|
end
|
|
113
111
|
|
|
114
112
|
# Its parsed renderers; a kept list that doesn't parse is the record's
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
|
-
require_relative "../
|
|
3
|
+
require_relative "../bundle_manifest"
|
|
4
4
|
require_relative "../memory_bundle/profile"
|
|
5
5
|
require_relative "../memory_bundle/source"
|
|
6
6
|
require_relative "../memory_bundle/system_bundle"
|
|
@@ -26,7 +26,7 @@ module Samagotchi
|
|
|
26
26
|
|
|
27
27
|
# The members installing +profile+ would install now.
|
|
28
28
|
def to_install(profile)
|
|
29
|
-
MemoryBundle::Profile.to_install(
|
|
29
|
+
MemoryBundle::Profile.to_install(BundleManifest.read(dir: dir(profile)))
|
|
30
30
|
end
|
|
31
31
|
|
|
32
32
|
private
|
|
@@ -478,7 +478,7 @@ module Samagotchi
|
|
|
478
478
|
|
|
479
479
|
def system_bundle_line(result, dry_run)
|
|
480
480
|
version = "v#{result.to || result.from}"
|
|
481
|
-
standing =
|
|
481
|
+
standing = InstalledBundles::FileStanding.clauses(MemoryBundle::SystemBundle::BUNDLE_NAME, nil, merged: Array(result.merged),
|
|
482
482
|
behind: Array(result.behind), dry_run: dry_run).join("; ")
|
|
483
483
|
text = case result.status
|
|
484
484
|
when :installed then dry_run ? "would install #{version}" : "#{version} installed"
|
|
@@ -61,8 +61,8 @@ module Samagotchi
|
|
|
61
61
|
# new worker's turn). A card shown between turns (github-pr's offer,
|
|
62
62
|
# btw, coordinator) keeps its buttons.
|
|
63
63
|
#
|
|
64
|
-
# A file from before the log (version 1)
|
|
65
|
-
#
|
|
64
|
+
# A file from before the log (version 1) is no longer read; its earlier
|
|
65
|
+
# cards do not show. Version 2 files saved since can still include readable +base_since+ places.
|
|
66
66
|
class CardStore
|
|
67
67
|
CAPACITY = 20
|
|
68
68
|
FORMAT_VERSION = 2
|
|
@@ -256,8 +256,6 @@ module Samagotchi
|
|
|
256
256
|
@turn_log = data[:turn_log].grep(String)
|
|
257
257
|
@failed_turn = data[:failed_turn] if data[:failed_turn].is_a?(String)
|
|
258
258
|
@entries = seeded(document.entries.map { |entry| entry.to_h.transform_keys(&:to_sym) })
|
|
259
|
-
elsif data[:turns].is_a?(Integer)
|
|
260
|
-
seed_v1(data)
|
|
261
259
|
end
|
|
262
260
|
rescue StateFormat::InvalidDocument => e
|
|
263
261
|
@format_read_only = true
|
|
@@ -269,21 +267,6 @@ module Samagotchi
|
|
|
269
267
|
@entries = []
|
|
270
268
|
end
|
|
271
269
|
|
|
272
|
-
# A file from before the turn log: each entry's place by the count it was
|
|
273
|
-
# saved with, killed turn included (nothing in it can say where a drifted
|
|
274
|
-
# card was). New openings add to it. The next save keeps +base_since+.
|
|
275
|
-
# Can go a retention period after the release that wrote version 2
|
|
276
|
-
# (compat shim cards_v1_seed: Compat::SHIMS).
|
|
277
|
-
def seed_v1(data)
|
|
278
|
-
killed_in_turn = data[:running] == true
|
|
279
|
-
turns_done = data[:turns] + (killed_in_turn ? 1 : 0)
|
|
280
|
-
olds = data[:entries].select { |entry| entry.is_a?(Hash) && entry[:turns].is_a?(Integer) }
|
|
281
|
-
@entries = seeded(olds.map do |entry|
|
|
282
|
-
turns = entry[:during] && killed_in_turn ? turns_done : entry[:turns]
|
|
283
|
-
entry.except(:turns).merge(base_since: [turns_done - turns - (entry[:in_turn] ? 1 : 0), 0].max)
|
|
284
|
-
end)
|
|
285
|
-
end
|
|
286
|
-
|
|
287
270
|
def seeded(entries)
|
|
288
271
|
entries.filter_map do |entry|
|
|
289
272
|
next unless entry.is_a?(Hash) && entry[:type].is_a?(String) && sound_place?(entry)
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Samagotchi
|
|
4
|
+
class Bridge
|
|
5
|
+
# What a running turn's plugin card waits as, from its data: "asks" (an
|
|
6
|
+
# action with a command: check-in's Nudge / Keep going / Stop), else
|
|
7
|
+
# "warn" (level warn: it stays in sight), else nil. The Ruby twin of the
|
|
8
|
+
# page's card_kinds.js cardWait for an in-turn card (TurnAccumulator folds
|
|
9
|
+
# in-turn cards only); spec/shared/card_wait_cases.json pins both.
|
|
10
|
+
module CardWait
|
|
11
|
+
module_function
|
|
12
|
+
|
|
13
|
+
# @param event [Hash] a card event or a drawing's card part event
|
|
14
|
+
# (symbol or string keys)
|
|
15
|
+
# @return [String, nil] "asks", "warn" or nil
|
|
16
|
+
def kind(event)
|
|
17
|
+
return nil unless event.is_a?(Hash)
|
|
18
|
+
return "asks" if Array(field(event, :actions)).any? { |action| command?(action) }
|
|
19
|
+
|
|
20
|
+
field(event, :level).to_s == "warn" ? "warn" : nil
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
# A JavaScript-truthy command (card_kinds.js: `a && a.command`).
|
|
24
|
+
def command?(action)
|
|
25
|
+
return false unless action.is_a?(Hash)
|
|
26
|
+
|
|
27
|
+
command = field(action, :command)
|
|
28
|
+
!(command.nil? || command == false || command == "" || command == 0)
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
def field(hash, key) = hash.key?(key) ? hash[key] : hash[key.to_s]
|
|
32
|
+
end
|
|
33
|
+
end
|
|
34
|
+
end
|
|
@@ -6,6 +6,7 @@ require_relative "../steer"
|
|
|
6
6
|
require_relative "../tool_output_cut"
|
|
7
7
|
require_relative "../tool_row_fields"
|
|
8
8
|
require_relative "../turn_origin"
|
|
9
|
+
require_relative "card_wait"
|
|
9
10
|
require_relative "turn_notice"
|
|
10
11
|
|
|
11
12
|
module Samagotchi
|
|
@@ -149,8 +150,8 @@ module Samagotchi
|
|
|
149
150
|
# tool_call_started and, once finished, its tool_call_completed (with
|
|
150
151
|
# the live activity: action, tool, params, status), a merged_input
|
|
151
152
|
# (the one synthetic type) per merged prompt, a steer-only
|
|
152
|
-
# pending_input_merged per steer, a reminder_injected,
|
|
153
|
-
# part's own event. Card parts only with +cards+ (a finished turn's
|
|
153
|
+
# pending_input_merged per steer, a reminder_injected, a notice
|
|
154
|
+
# part's own event, and a part_settled per settle part. Card parts only with +cards+ (a finished turn's
|
|
154
155
|
# drawing, chi web's unfold of it): a running turn's join gets its cards
|
|
155
156
|
# from CardStore's snapshot.
|
|
156
157
|
# @param started_at [String, nil] the turn's start, on turn_started
|
|
@@ -204,6 +205,11 @@ module Samagotchi
|
|
|
204
205
|
|
|
205
206
|
close_text.call
|
|
206
207
|
events << part[:event].merge(type: :card, in_turn: true)
|
|
208
|
+
when "settle"
|
|
209
|
+
# Where a card stopped waiting (#fold_card). A join without
|
|
210
|
+
# cards gets it too: a page with no such card ignores it. A
|
|
211
|
+
# mark, not a row: an open text stays open.
|
|
212
|
+
events << { type: :part_settled, of: part[:of], id: part[:id], was: part[:was], now: part[:now] }
|
|
207
213
|
end
|
|
208
214
|
end
|
|
209
215
|
events
|
|
@@ -477,11 +483,23 @@ module Samagotchi
|
|
|
477
483
|
private_constant :CARD_FIELDS
|
|
478
484
|
|
|
479
485
|
# A card the turn shows in its step; one with an earlier card's id
|
|
480
|
-
# replaces that part where it was.
|
|
486
|
+
# replaces that part where it was (its arrival). When that update
|
|
487
|
+
# ends a wait (CardWait: asking, a warning) for another (none, a
|
|
488
|
+
# warning), a settle part marks the place it stopped waiting, where
|
|
489
|
+
# live moved it (cards_place.js upsertCard): { kind: "settle", of:
|
|
490
|
+
# "card", id:, was:, now: }. A card that starts waiting later gets
|
|
491
|
+
# none (live doesn't move it back). A question needs no mark: its own
|
|
492
|
+
# notice parts (question_requested, question_answered /
|
|
493
|
+
# question_cancelled) are its arrival and its settle.
|
|
481
494
|
def fold_card(parts, event)
|
|
482
495
|
card = { kind: "card", id: event[:id], event: Marshal.load(Marshal.dump(event.slice(*CARD_FIELDS))) }
|
|
483
496
|
index = parts.index { |part| part[:kind] == "card" && part[:id] == card[:id] }
|
|
484
|
-
|
|
497
|
+
return parts << card unless index
|
|
498
|
+
|
|
499
|
+
was = CardWait.kind(parts[index][:event])
|
|
500
|
+
parts[index] = card
|
|
501
|
+
now = CardWait.kind(card[:event])
|
|
502
|
+
parts << { kind: "settle", of: "card", id: card[:id], was: was, now: now } if was && was != now && now != "asks"
|
|
485
503
|
end
|
|
486
504
|
|
|
487
505
|
# The turn's final fold to the hook (#initialize's on_turn_end).
|
data/lib/samagotchi/bridge.rb
CHANGED
|
@@ -39,6 +39,7 @@ require_relative "proxy_trace"
|
|
|
39
39
|
require_relative "version"
|
|
40
40
|
require_relative "worker_sidecar"
|
|
41
41
|
require_relative "worker_link"
|
|
42
|
+
require_relative "working_set"
|
|
42
43
|
require_relative "relay_verifier"
|
|
43
44
|
require_relative "relay_watcher"
|
|
44
45
|
require_relative "reply_wait"
|
|
@@ -92,6 +93,7 @@ module Samagotchi
|
|
|
92
93
|
request_recap: "idle-recap monitor",
|
|
93
94
|
reserve_enqueued_id: "turn-state monitor",
|
|
94
95
|
working_set_snapshot: "idle working-set snapshot under event lock",
|
|
96
|
+
working_set_item: "turn view under its mutex, else session messages under event lock",
|
|
95
97
|
"running_turn_messages=": "callback writer; Bridge lifecycle",
|
|
96
98
|
saved_recap: "recap mutex; replace-only session messages",
|
|
97
99
|
session: "session reference; messages are replace-only",
|
|
@@ -803,11 +805,15 @@ module Samagotchi
|
|
|
803
805
|
# participant_client_id: it reads a participant's client id as
|
|
804
806
|
# participant:<id>; chi web sends a worker without it review:<id>
|
|
805
807
|
# (Delivery::PARTICIPANT_ID_FEATURE).
|
|
808
|
+
# working_set_item: GET working_set/item answers one item's timeline,
|
|
809
|
+
# the running turn's mid-turn (WorkingSet::ITEM_FEATURE); chi web asks
|
|
810
|
+
# an older worker for its whole snapshot instead.
|
|
806
811
|
FEATURES = ["restart", "task_stop", "reparent", Delivery::QUEUE_FEATURE, ReplyWait::TURN_IDS_FEATURE,
|
|
807
812
|
VerifyAnchor::FEATURE, ReviseAnchor::FEATURE,
|
|
808
813
|
SessionInbox::UNQUEUE_FEATURE, Delivery::REVIEW_FEATURE, Delivery::PAIR_FEATURE, TurnDrawings::FEATURE,
|
|
809
814
|
WorkerLink::ACTIVITY_FEATURE, ObjectivesTrack::FEATURE, Delivery::OWN_TURN_STEER_FEATURE,
|
|
810
|
-
Delivery::CANCEL_TURN_ID_FEATURE, ReviseAnchor::PARTICIPANT_FEATURE, Delivery::PARTICIPANT_ID_FEATURE
|
|
815
|
+
Delivery::CANCEL_TURN_ID_FEATURE, ReviseAnchor::PARTICIPANT_FEATURE, Delivery::PARTICIPANT_ID_FEATURE,
|
|
816
|
+
WorkingSet::ITEM_FEATURE].freeze
|
|
811
817
|
|
|
812
818
|
# The routes, by method and what follows /session/:id/: a handler takes
|
|
813
819
|
# the session id and the request body and returns [headers, status, body].
|
|
@@ -832,9 +838,13 @@ module Samagotchi
|
|
|
832
838
|
%w[GET state] => :handle_state,
|
|
833
839
|
%w[GET stats] => :handle_stats,
|
|
834
840
|
%w[GET snapshot] => :handle_snapshot,
|
|
835
|
-
%w[GET tail] => :handle_tail
|
|
841
|
+
%w[GET tail] => :handle_tail,
|
|
842
|
+
%w[GET working_set/item] => :handle_working_set_item
|
|
836
843
|
}.freeze
|
|
837
844
|
ROUTE_PATH = %r{\A/session/([^/]+)/(.+)\z}u
|
|
845
|
+
# The handlers that take the request's query string as a third
|
|
846
|
+
# argument (#dispatch); every other one gets the id and the body only.
|
|
847
|
+
QUERY_HANDLERS = %i[handle_tail handle_working_set_item].freeze
|
|
838
848
|
|
|
839
849
|
# @return [Array(Symbol, String), nil] the handler and the session id, or
|
|
840
850
|
# nil when no route takes this method and path
|
|
@@ -848,10 +858,10 @@ module Samagotchi
|
|
|
848
858
|
# #own_session?), and a handler that raises answers 500 bridge_error,
|
|
849
859
|
# logged (the connection thread doesn't report).
|
|
850
860
|
# @return [Array(Hash, Integer, Hash)] headers, status, body
|
|
851
|
-
# Only
|
|
861
|
+
# Only a QUERY_HANDLERS handler takes the request's +query+.
|
|
852
862
|
def dispatch(handler, session_id, body, query = nil)
|
|
853
863
|
return [{}, 404, { error: "unknown_session" }] unless own_session?(session_id)
|
|
854
|
-
return
|
|
864
|
+
return send(handler, session_id, body, query) if QUERY_HANDLERS.include?(handler)
|
|
855
865
|
|
|
856
866
|
send(handler, session_id, body)
|
|
857
867
|
rescue StandardError => e
|
|
@@ -1538,8 +1548,8 @@ module Samagotchi
|
|
|
1538
1548
|
end
|
|
1539
1549
|
|
|
1540
1550
|
# The page's light re-read (#tail_frame): no message list. `?turn_id=`:
|
|
1541
|
-
# that turn's answer (a queued turn's page re-reads late).
|
|
1542
|
-
#
|
|
1551
|
+
# that turn's answer (a queued turn's page re-reads late). A handler
|
|
1552
|
+
# that gets the query (QUERY_HANDLERS); an older worker's route
|
|
1543
1553
|
# ignores it and sends the newest answer.
|
|
1544
1554
|
def handle_tail(_session_id, _body = nil, query = nil)
|
|
1545
1555
|
turn_id = query && URI.decode_www_form(query).to_h["turn_id"].to_s
|
|
@@ -1548,6 +1558,28 @@ module Samagotchi
|
|
|
1548
1558
|
[{}, 200, tail_frame]
|
|
1549
1559
|
end
|
|
1550
1560
|
|
|
1561
|
+
# What the model has of one item now (Engine#working_set_item: the
|
|
1562
|
+
# running turn's view as of its last request, else the session's),
|
|
1563
|
+
# chi web's item route's answer. `?kind=&key=[&now=1][&latest=1]`
|
|
1564
|
+
# (latest: the peek's events and counts only); 400 for a
|
|
1565
|
+
# kind not in WorkingSet::KINDS or a blank key, in chi web's words.
|
|
1566
|
+
# Owner-only stays chi web's: the Bridge's gate is its secret.
|
|
1567
|
+
def handle_working_set_item(_session_id, _body = nil, query = nil)
|
|
1568
|
+
params = begin
|
|
1569
|
+
URI.decode_www_form(query.to_s).to_h
|
|
1570
|
+
rescue ArgumentError
|
|
1571
|
+
{}
|
|
1572
|
+
end
|
|
1573
|
+
kind = params["kind"].to_s
|
|
1574
|
+
key = params["key"].to_s
|
|
1575
|
+
unless WorkingSet::KINDS.include?(kind) && !key.strip.empty?
|
|
1576
|
+
return [{}, 400, { error: "invalid_item", detail: WorkingSet::INVALID_ITEM }]
|
|
1577
|
+
end
|
|
1578
|
+
|
|
1579
|
+
item = @engine.working_set_item(kind: kind, key: key, now: params["now"] == "1", latest: params["latest"] == "1")
|
|
1580
|
+
item ? [{}, 200, item] : [{}, 409, { error: "no_session" }]
|
|
1581
|
+
end
|
|
1582
|
+
|
|
1551
1583
|
# The stream cursor for +seq+ in this worker.
|
|
1552
1584
|
def event_id(seq)
|
|
1553
1585
|
EventId.format(seq.to_i, @epoch)
|