samagotchi 0.178.0 → 0.180.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 +58 -1
- data/docs/architecture.md +4 -2
- data/docs/bundles.md +48 -8
- data/docs/cli.md +3 -1
- data/docs/configuration.md +1 -1
- data/docs/context.md +32 -1
- data/docs/guardrails.md +2 -1
- data/docs/internals/attached-context.md +26 -4
- data/docs/internals/background-tasks.md +5 -1
- data/docs/internals/block-renderers.md +4 -3
- data/docs/internals/bridge.md +11 -2
- data/docs/internals/bundles.md +65 -34
- data/docs/internals/engine.md +1 -1
- data/docs/internals/web-frontend.md +81 -3
- data/docs/plugins.md +20 -5
- data/docs/releasing.md +3 -3
- data/docs/scheduling.md +4 -0
- data/docs/sessions.md +8 -2
- data/docs/testing.md +8 -1
- data/lib/samagotchi/block_renderers.rb +33 -16
- data/lib/samagotchi/bootstrap/bundles.rb +2 -2
- data/lib/samagotchi/bootstrap_command.rb +1 -1
- data/lib/samagotchi/bridge/card_wait.rb +34 -0
- data/lib/samagotchi/bridge/turn_accumulator.rb +22 -4
- 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 +22 -18
- data/lib/samagotchi/bundle_manifest.rb +579 -0
- data/lib/samagotchi/bundle_needs.rb +9 -8
- data/lib/samagotchi/bundle_settings_check.rb +13 -9
- 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/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 -29
- data/lib/samagotchi/context_sources.rb +42 -12
- data/lib/samagotchi/engine/messages.rb +1 -1
- 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/outside.rb +3 -3
- data/lib/samagotchi/{memory_bundle → installed_bundles}/bundle_hook.rb +1 -1
- data/lib/samagotchi/installed_bundles/dir.rb +91 -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 +65 -0
- data/lib/samagotchi/installed_bundles.rb +105 -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 +19 -16
- 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/self_report.rb +14 -14
- data/lib/samagotchi/session_access/local.rb +16 -1
- data/lib/samagotchi/session_access/remote.rb +2 -1
- data/lib/samagotchi/session_config.rb +29 -19
- data/lib/samagotchi/session_manager/running_tasks.rb +15 -2
- data/lib/samagotchi/session_retention.rb +13 -4
- data/lib/samagotchi/session_stores.rb +3 -0
- data/lib/samagotchi/system_prompt.rb +4 -4
- data/lib/samagotchi/terminal_ui/attach_launcher.rb +5 -1
- data/lib/samagotchi/terminal_ui/attached_loop.rb +1 -1
- data/lib/samagotchi/terminal_ui/formatting.rb +15 -5
- data/lib/samagotchi/terminal_ui/join_replay.rb +1 -1
- 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 +12 -3
- data/lib/samagotchi/update_command.rb +4 -4
- data/lib/samagotchi/version.rb +1 -1
- data/lib/samagotchi/web/app.rb +14 -1
- 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/app.js +13 -1
- 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/context_chips.js +184 -49
- data/lib/samagotchi/web/public/ctx.js +1 -1
- data/lib/samagotchi/web/public/history_shape.js +8 -3
- data/lib/samagotchi/web/public/index.html +66 -0
- data/lib/samagotchi/web/public/peer_chip.js +171 -0
- data/lib/samagotchi/web/public/peer_data.js +119 -0
- data/lib/samagotchi/web/public/peer_exchange.js +83 -0
- data/lib/samagotchi/web/public/peer_links.js +161 -0
- data/lib/samagotchi/web/public/peer_note.js +49 -0
- data/lib/samagotchi/web/public/session_view.js +6 -1
- data/lib/samagotchi/web/public/stream_handlers.js +17 -4
- data/lib/samagotchi/web/public/turn_block.js +46 -8
- data/lib/samagotchi/web/public/turn_html.js +11 -2
- data/lib/samagotchi/web/public/turn_settle.js +117 -0
- data/lib/samagotchi/web/push/notifier.rb +2 -2
- data/lib/samagotchi/web/session_access_routes.rb +21 -1
- data/lib/samagotchi/web/session_hub.rb +20 -4
- data/lib/samagotchi/worker_boot.rb +4 -1
- metadata +24 -12
- data/lib/samagotchi/memory_bundle/manifest.rb +0 -581
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.
|
|
@@ -43,13 +49,13 @@ A new session field is one `Session::FIELDS` row, plus a `SessionSetup` member w
|
|
|
43
49
|
|
|
44
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`). **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.
|
|
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
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
|
|
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.
|
|
@@ -306,6 +308,10 @@ group and also answers them as module calls (`SpecWaiting.pop!`, for a stubbed l
|
|
|
306
308
|
- `time_bound(seconds, below: nil)`: a wall-clock upper bound, scaled and kept under `below:` (rule 5).
|
|
307
309
|
- `eventually(timeout: 5) { expect(…) }` (spec only) retries until the expectations hold, then re-raises the last
|
|
308
310
|
failure prefixed `still failing after 5 s:`, so the matcher's own expected/got is in the message.
|
|
311
|
+
- `gone_soon?(pid, group: false, timeout: 2)` (spec only): "stopped" after a stop returned, a pid (or with
|
|
312
|
+
`group: true` its group) gone within 2 s. Never an immediate `kill(0)`: a stopped process can answer it for a
|
|
313
|
+
moment (on Linux a dying process drops its `flock` before it is reaped, and `Leftovers.stop_group` returns on the
|
|
314
|
+
log's release).
|
|
309
315
|
|
|
310
316
|
One formatter builds the failure text of `wait_for`, `join!` (which adds "to finish") and `pop!`:
|
|
311
317
|
|
|
@@ -399,6 +405,7 @@ any other file requires it, so a spec file run alone still finds its requires. E
|
|
|
399
405
|
| `recording_surface.rb` | `RecordingSurface`: a `TerminalUI::Surface` that records commits and slots instead of drawing |
|
|
400
406
|
| `remote_backend.rb` | `RemoteBackend`: `SessionAccess::Remote` against chi web's Rack app in this process (no socket, LAN token gate) |
|
|
401
407
|
| `reply_wait_looks.rb` | `ReplyWaitLooks`: counts a `ReplyWait`'s polls, so a step waits for the looks instead of a delay |
|
|
408
|
+
| `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
409
|
| `stamps.rb` | *helper*: `next_stamp`, distinct ordered times for the lib's `now:` seams; the pinned history clock |
|
|
403
410
|
| `task_dirs.rb` | `with_task_dir`: a tasks' folder of its own, every task stopped and its recorders joined after |
|
|
404
411
|
| `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
|
|
@@ -38,7 +36,8 @@ module Samagotchi
|
|
|
38
36
|
# Languages core draws itself: a bundle's renderer for one would be a
|
|
39
37
|
# second drawer for the same block.
|
|
40
38
|
RESERVED = [InlineWidgets::LANG].freeze
|
|
41
|
-
#
|
|
39
|
+
# What .renderers and .too_new? have logged in this process: [bundle,
|
|
40
|
+
# problem] pairs, and [bundle, version, refusal] for a bundle too new.
|
|
42
41
|
WARNED = Set.new
|
|
43
42
|
WARNED_LOCK = Mutex.new
|
|
44
43
|
|
|
@@ -70,7 +69,7 @@ module Samagotchi
|
|
|
70
69
|
raise Invalid, "block_renderers: #{lang} is drawn by chi itself; a bundle can't render it" if RESERVED.include?(lang)
|
|
71
70
|
|
|
72
71
|
load = data["load"]
|
|
73
|
-
unless load.is_a?(Array) && !load.empty? && load.all? { |file| file.is_a?(String) && file.match?(
|
|
72
|
+
unless load.is_a?(Array) && !load.empty? && load.all? { |file| file.is_a?(String) && file.match?(BundleManifest::SCRIPT_FILE) }
|
|
74
73
|
raise Invalid, "block_renderers: #{lang}'s load must be a non-empty list of file names in scripts/, not #{load.inspect}"
|
|
75
74
|
end
|
|
76
75
|
|
|
@@ -79,15 +78,16 @@ module Samagotchi
|
|
|
79
78
|
|
|
80
79
|
# What the installed bundles draw: the first bundle by name wins a
|
|
81
80
|
# language. A bundle whose requires_chi this chi doesn't meet, or whose list
|
|
82
|
-
# doesn't parse
|
|
81
|
+
# doesn't parse, is skipped (each logged once); a record that doesn't read
|
|
82
|
+
# lists none.
|
|
83
83
|
# @return [Array<Installed>]
|
|
84
84
|
def for_installed
|
|
85
85
|
taken = {}
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
next if manifest.requires_chi_failure(VERSION)
|
|
86
|
+
InstalledBundles.standings do |standing|
|
|
87
|
+
next if too_new?(standing)
|
|
89
88
|
|
|
90
|
-
|
|
89
|
+
bundle = standing.name
|
|
90
|
+
renderers(bundle, standing.record.manifest).each do |renderer|
|
|
91
91
|
taken[renderer.lang] ||= Installed.new(lang: renderer.lang, bundle: bundle, files: renderer.load)
|
|
92
92
|
end
|
|
93
93
|
end
|
|
@@ -104,12 +104,29 @@ module Samagotchi
|
|
|
104
104
|
def script_path(bundle, file)
|
|
105
105
|
return nil unless for_installed.any? { |renderer| renderer.bundle == bundle && renderer.files.include?(file) }
|
|
106
106
|
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
raise Invalid,
|
|
107
|
+
installed = InstalledBundles::Dir.new(name: bundle)
|
|
108
|
+
refusal = installed.file_refusal(:scripts, file, InstalledBundles.standing(bundle)&.record&.scripts&.fetch(file, nil))
|
|
109
|
+
raise Invalid, refusal.text if refusal
|
|
110
110
|
|
|
111
|
-
File.join(
|
|
111
|
+
File.join(installed.scripts_dir, file)
|
|
112
|
+
end
|
|
113
|
+
|
|
114
|
+
# A bundle this chi is too old for (the verdict's :too_new) draws
|
|
115
|
+
# nothing: skip it, and say so once per process per bundle and version,
|
|
116
|
+
# only when it declares renderers (as ContextProviders.too_new? does).
|
|
117
|
+
# @param standing [InstalledBundles::Standing]
|
|
118
|
+
def too_new?(standing)
|
|
119
|
+
return false unless standing.too_new?
|
|
120
|
+
|
|
121
|
+
manifest = standing.record.manifest
|
|
122
|
+
if manifest.block_renderers? &&
|
|
123
|
+
WARNED_LOCK.synchronize { WARNED.add?([standing.name, manifest.version.to_s, standing.refusal.text]) }
|
|
124
|
+
Log.warn(:web, "block_renderers_too_new", bundle: standing.name, version: manifest.version.to_s,
|
|
125
|
+
requires_chi: manifest.requires_chi.to_s, msg: standing.refusal.text)
|
|
126
|
+
end
|
|
127
|
+
true
|
|
112
128
|
end
|
|
129
|
+
private_class_method :too_new?
|
|
113
130
|
|
|
114
131
|
# Its parsed renderers; a kept list that doesn't parse is the record's
|
|
115
132
|
# mirror, else none. Logged once per bundle and problem: this runs on each
|
|
@@ -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"
|
|
@@ -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).
|
|
@@ -136,11 +136,11 @@ module Samagotchi
|
|
|
136
136
|
@text = File.read(path("manifest.yml"))
|
|
137
137
|
Dir.mktmpdir("chi-bundle-check-") do |tmp|
|
|
138
138
|
File.write(File.join(tmp, "manifest.yml"), MemoryBundle::Shas.parseable(@text))
|
|
139
|
-
|
|
140
|
-
rescue
|
|
139
|
+
BundleManifest.read(dir: tmp)
|
|
140
|
+
rescue BundleManifest::HooksRetired => e
|
|
141
141
|
add(:error, :"hooks-retired", "manifest.yml", e.message, line: manifest_line("hooks"), fix: hooks_fix)
|
|
142
142
|
nil
|
|
143
|
-
rescue
|
|
143
|
+
rescue BundleManifest::ValidationError => e
|
|
144
144
|
add(:error, :manifest, "manifest.yml", e.message.gsub(tmp, display(@dir)))
|
|
145
145
|
nil
|
|
146
146
|
end
|
|
@@ -149,10 +149,10 @@ module Samagotchi
|
|
|
149
149
|
# A source with hooks/*.rb (listed or not) can't be installed: the run
|
|
150
150
|
# stops there, as after a manifest error (Manifest::HooksRetired.refuse_source_files).
|
|
151
151
|
def hooks_retired?
|
|
152
|
-
files =
|
|
152
|
+
files = BundleManifest::HooksRetired.files_in(@dir)
|
|
153
153
|
return false if files.empty?
|
|
154
154
|
|
|
155
|
-
add(:error, :"hooks-retired", "hooks/",
|
|
155
|
+
add(:error, :"hooks-retired", "hooks/", BundleManifest::HooksRetired.for_files(files).message, fix: hooks_fix)
|
|
156
156
|
true
|
|
157
157
|
end
|
|
158
158
|
|
|
@@ -173,7 +173,7 @@ module Samagotchi
|
|
|
173
173
|
# only the unknown-key line, as check_floor's call floor does today.
|
|
174
174
|
def check_keys(manifest)
|
|
175
175
|
manifest.unknown_keys.each do |key|
|
|
176
|
-
add(:warn, :"unknown-key", "manifest.yml",
|
|
176
|
+
add(:warn, :"unknown-key", "manifest.yml", BundleManifest.unknown_key_line(key), line: manifest_line(key),
|
|
177
177
|
fix: "update chi, or remove #{key}: if it's a typo")
|
|
178
178
|
end
|
|
179
179
|
check_key_floor(manifest) unless @installed
|
|
@@ -268,7 +268,7 @@ module Samagotchi
|
|
|
268
268
|
|
|
269
269
|
def check_requires_chi(manifest)
|
|
270
270
|
line = manifest_line("requires_chi")
|
|
271
|
-
if (failure =
|
|
271
|
+
if (failure = BundleManifest.requires_chi_failure(manifest.requires_chi, VERSION))
|
|
272
272
|
@too_new = true
|
|
273
273
|
add(:error, :"requires-chi", "manifest.yml", "this chi can't load it: #{failure}", line: line,
|
|
274
274
|
fix: "chi update, or lower requires_chi")
|
|
@@ -338,11 +338,11 @@ module Samagotchi
|
|
|
338
338
|
end
|
|
339
339
|
|
|
340
340
|
# The installed same-named bundle's record; an unreadable one as
|
|
341
|
-
#
|
|
341
|
+
# InstalledBundles::Record.unreadable.
|
|
342
342
|
def installed_record(name)
|
|
343
343
|
MemoryBundle::Provenance.new(name: name).record
|
|
344
344
|
rescue JSON::ParserError, SystemCallError => e
|
|
345
|
-
|
|
345
|
+
InstalledBundles::Record.unreadable(name, "#{e.class}: #{e.message.lines.first&.strip}")
|
|
346
346
|
end
|
|
347
347
|
|
|
348
348
|
def unreadable_clash(name, error)
|
|
@@ -373,7 +373,7 @@ module Samagotchi
|
|
|
373
373
|
# The loaders refuse a bundle requires_chi rules out: that's the requires-chi error.
|
|
374
374
|
result.failures.each { |failure| install_failure(failure) unless @too_new && failure.reason.include?("it requires chi") }
|
|
375
375
|
report_registered(manifest, result.registered)
|
|
376
|
-
rescue MemoryBundle::Installer::InstallError,
|
|
376
|
+
rescue MemoryBundle::Installer::InstallError, BundleManifest::ValidationError => e
|
|
377
377
|
add(:error, :install, "manifest.yml", e.message)
|
|
378
378
|
rescue StandardError => e
|
|
379
379
|
# Whatever else the install or the load raised: one finding, not a trace.
|
|
@@ -24,7 +24,7 @@ module Samagotchi
|
|
|
24
24
|
|
|
25
25
|
module_function
|
|
26
26
|
|
|
27
|
-
# @param bundle [
|
|
27
|
+
# @param bundle [InstalledBundles::Record]
|
|
28
28
|
# @return [Array<Found>] its warnings and errors; never raises for the bundle
|
|
29
29
|
def run(bundle)
|
|
30
30
|
$stdout.flush
|
|
@@ -59,7 +59,7 @@ module Samagotchi
|
|
|
59
59
|
|
|
60
60
|
# What the child sends: an edited file, which the copy's own shas can't
|
|
61
61
|
# tell, a manifest key that doesn't parse (the copy holds the mirror's
|
|
62
|
-
# value or none:
|
|
62
|
+
# value or none: InstalledBundles::Manifest#key_problems), and Check's warnings
|
|
63
63
|
# and errors, naming the installed bundle's folder rather than the copy's.
|
|
64
64
|
def answer_of(bundle)
|
|
65
65
|
edited = MemoryBundle::ShippedUpdate.edited_executables(bundle.name, bundle).map do |file|
|
|
@@ -109,7 +109,7 @@ module Samagotchi
|
|
|
109
109
|
# Installs the tried bundle, then the shipped guardrails and
|
|
110
110
|
# cost-cap (unless it is one of them), each as `chi bundle install
|
|
111
111
|
# PATH --force` in one child chi with the sandbox's environment.
|
|
112
|
-
# @return [
|
|
112
|
+
# @return [BundleManifest]
|
|
113
113
|
# @raise [Error] what the first install that failed printed
|
|
114
114
|
def install
|
|
115
115
|
paths = [@path] + %w[guardrails cost-cap].reject { |name| @manifest.name == name }
|
|
@@ -171,13 +171,13 @@ module Samagotchi
|
|
|
171
171
|
raise Error, "chi bundle try: stale or placeholder sha256 in manifest.yml; run chi bundle check --fix"
|
|
172
172
|
end
|
|
173
173
|
|
|
174
|
-
@manifest =
|
|
174
|
+
@manifest = BundleManifest.read(dir: @path)
|
|
175
175
|
if @manifest.meta?
|
|
176
176
|
raise Error.new("chi bundle try: profile bundles cannot be tried directly", status: CLI::Exit::USAGE)
|
|
177
177
|
end
|
|
178
178
|
|
|
179
179
|
@manifest
|
|
180
|
-
rescue
|
|
180
|
+
rescue BundleManifest::ValidationError => e
|
|
181
181
|
raise Error, "chi bundle try: #{e.message}"
|
|
182
182
|
rescue MemoryBundle::Shas::Error => e
|
|
183
183
|
raise Error, "chi bundle try: #{e.message}"
|
|
@@ -109,6 +109,10 @@ module Samagotchi
|
|
|
109
109
|
STATUS_HELP = "Usage: chi bundle status [<bundle>]"
|
|
110
110
|
DIFF_HELP = "Usage: chi bundle diff <bundle> [file]"
|
|
111
111
|
LIST_HELP = "Usage: chi bundle list"
|
|
112
|
+
# What `chi bundle status NAME` says after a plugin's state
|
|
113
|
+
# (MemoryBundle::Status.plugin_status) that keeps it from loading.
|
|
114
|
+
PLUGIN_NOTES = { "modified" => " (edited after install: not loaded; reinstall the bundle)",
|
|
115
|
+
"unrecorded" => " (no sha256 recorded: not loaded; reinstall the bundle)" }.freeze
|
|
112
116
|
|
|
113
117
|
# The subcommands' flags: --help only; a word not starting with -- is
|
|
114
118
|
# a positional (install's source, -h included). --scope takes whatever
|
|
@@ -282,10 +286,10 @@ module Samagotchi
|
|
|
282
286
|
# @return [Array(MemoryBundle::PreparedSource, String), nil]
|
|
283
287
|
def prepare_or_fail(expanded_source, word)
|
|
284
288
|
prepared = Samagotchi::MemoryBundle::PreparedSource.prepare(expanded_source)
|
|
285
|
-
Samagotchi::
|
|
286
|
-
named = [prepared, Samagotchi::
|
|
289
|
+
Samagotchi::BundleManifest::HooksRetired.refuse_source_files(prepared.dir)
|
|
290
|
+
named = [prepared, Samagotchi::BundleManifest.read(dir: prepared.dir).name]
|
|
287
291
|
rescue Samagotchi::MemoryBundle::SourceNormalizer::UnknownSourceError,
|
|
288
|
-
Samagotchi::
|
|
292
|
+
Samagotchi::BundleManifest::ValidationError => e
|
|
289
293
|
@stderr.puts "#{word} failed: #{e.message}"
|
|
290
294
|
ensure
|
|
291
295
|
# Any failure (an unexpected error too) removes the extract.
|
|
@@ -305,7 +309,7 @@ module Samagotchi
|
|
|
305
309
|
identity = Samagotchi::MemoryBundle::SourceIdentity.of(expanded_source)
|
|
306
310
|
return false unless identity
|
|
307
311
|
|
|
308
|
-
other, = Samagotchi::
|
|
312
|
+
other, = Samagotchi::InstalledBundles.each.find do |name, bundle|
|
|
309
313
|
name != bundle_name && !bundle.error? && Samagotchi::MemoryBundle::SourceIdentity.of(bundle.source) == identity
|
|
310
314
|
end
|
|
311
315
|
return false unless other
|
|
@@ -343,13 +347,13 @@ module Samagotchi
|
|
|
343
347
|
return unless plugin && manifest&.plugin
|
|
344
348
|
|
|
345
349
|
# Installed with --force past its requires_chi: the Engine won't load it.
|
|
346
|
-
failure = Samagotchi::
|
|
350
|
+
failure = Samagotchi::BundleManifest.requires_chi_failure(manifest.requires_chi, Samagotchi::VERSION)
|
|
347
351
|
@stdout.puts "Plugin: #{manifest.plugin[:file]} (#{failure ? "won't load on this chi: #{failure}" : "loads at the next chi start"})"
|
|
348
352
|
end
|
|
349
353
|
|
|
350
354
|
# @return [Integer] 0
|
|
351
355
|
def print_provenance(bundle_name, manifest)
|
|
352
|
-
@stdout.puts "Provenance written to: #{Samagotchi::
|
|
356
|
+
@stdout.puts "Provenance written to: #{Samagotchi::InstalledBundles.dir}/#{bundle_name}/" if manifest
|
|
353
357
|
0
|
|
354
358
|
end
|
|
355
359
|
|
|
@@ -370,9 +374,9 @@ module Samagotchi
|
|
|
370
374
|
# result, with how many sessions and the command for each. Nothing when the
|
|
371
375
|
# plugin is unchanged or there never was one, nothing with no worker that
|
|
372
376
|
# can be restarted.
|
|
373
|
-
# @param before [
|
|
377
|
+
# @param before [InstalledBundles::Record, nil] the bundle's record as it was before
|
|
374
378
|
# the run (an uninstall deletes it, so take it first)
|
|
375
|
-
# @param manifest [
|
|
379
|
+
# @param manifest [BundleManifest, nil] the manifest this run
|
|
376
380
|
# installed; nil for an uninstall
|
|
377
381
|
# @param installer [Installer, nil] the run, for what it wrote to the plugin
|
|
378
382
|
def restart_hint(before, manifest = nil, installer = nil)
|
|
@@ -402,7 +406,7 @@ module Samagotchi
|
|
|
402
406
|
|
|
403
407
|
# @return [Integer] 0 all resolved, CONFLICTS_KEPT kept some edits
|
|
404
408
|
def upgrade_conflicts(installer, bundle_name, expanded_source, agent)
|
|
405
|
-
standing = Samagotchi::
|
|
409
|
+
standing = Samagotchi::InstalledBundles::FileStanding
|
|
406
410
|
@stdout.puts "\n#{standing.stay_behind(installer.behind.size)}: #{installer.behind.map(&:file).join(", ")}"
|
|
407
411
|
launch = if agent.nil? && @stdin.tty?
|
|
408
412
|
@stdout.print "Launch an interactive agent to merge them? [y/N] "
|
|
@@ -444,7 +448,7 @@ module Samagotchi
|
|
|
444
448
|
marked, clean = changed.partition { |_, info| merger.markers?(info[:current]) }
|
|
445
449
|
settled = Samagotchi::MemoryBundle::Provenance.new(name: bundle_name).resolve_conflicts(clean.to_h)
|
|
446
450
|
gone = clean.map(&:first) - settled
|
|
447
|
-
standing = Samagotchi::
|
|
451
|
+
standing = Samagotchi::InstalledBundles::FileStanding
|
|
448
452
|
untouched.each { |key, _| @stdout.puts standing.still_behind(:untouched, key) }
|
|
449
453
|
marked.each { |key, _| @stdout.puts standing.still_behind(:markers, key) }
|
|
450
454
|
gone.each { |key| @stdout.puts standing.still_behind(:incoming_gone, key) }
|
|
@@ -508,7 +512,7 @@ module Samagotchi
|
|
|
508
512
|
lines.each { |line| @stdout.puts " #{line}" }
|
|
509
513
|
@stdout.puts "(dry-run: no changes written)" if dry_run
|
|
510
514
|
result.failed? ? 1 : 0
|
|
511
|
-
rescue Samagotchi::
|
|
515
|
+
rescue Samagotchi::BundleManifest::ValidationError => e
|
|
512
516
|
@stderr.puts "#{word} failed: #{e.message}"
|
|
513
517
|
1
|
|
514
518
|
end
|
|
@@ -558,7 +562,7 @@ module Samagotchi
|
|
|
558
562
|
else
|
|
559
563
|
@stdout.puts "Target: #{st.target_dir}"
|
|
560
564
|
end
|
|
561
|
-
standing = Samagotchi::
|
|
565
|
+
standing = Samagotchi::InstalledBundles::FileStanding
|
|
562
566
|
st.files.each do |k, info|
|
|
563
567
|
next @stdout.puts(" #{k}: unchecked") if info[:unchecked]
|
|
564
568
|
|
|
@@ -584,7 +588,7 @@ module Samagotchi
|
|
|
584
588
|
print_assets("Rules", st.rules, " (edited after install: not loaded; reinstall the bundle)")
|
|
585
589
|
print_assets("Scripts", st.scripts, " (edited after install: the next install replaces it, a copy kept in the trash)")
|
|
586
590
|
if (plugin = st.plugin)
|
|
587
|
-
note = plugin[:state]
|
|
591
|
+
note = PLUGIN_NOTES.fetch(plugin[:state], "")
|
|
588
592
|
@stdout.puts " Plugin: #{plugin[:file]} [#{plugin[:state]}]#{note}"
|
|
589
593
|
@stdout.puts " requires_chi: #{plugin[:requires_chi]}" if plugin[:requires_chi]
|
|
590
594
|
@stdout.puts " not loaded: #{plugin[:requires_failure]}" if plugin[:requires_failure]
|
|
@@ -595,7 +599,7 @@ module Samagotchi
|
|
|
595
599
|
@stdout.puts " includes #{member} [#{state}]"
|
|
596
600
|
end
|
|
597
601
|
else
|
|
598
|
-
bundles = Samagotchi::
|
|
602
|
+
bundles = Samagotchi::InstalledBundles.each.to_a
|
|
599
603
|
@stdout.puts "No installed bundles." if bundles.empty?
|
|
600
604
|
bundles.each do |bname, record|
|
|
601
605
|
next @stdout.puts(" #{bname} (manifest.json unreadable)") if record.error?
|
|
@@ -708,9 +712,9 @@ module Samagotchi
|
|
|
708
712
|
# A rule or script keeps no base text: its recorded and current sha256.
|
|
709
713
|
def diff_asset(asset)
|
|
710
714
|
@stdout.puts "=== #{asset.label} ==="
|
|
711
|
-
current = File.file?(asset.path) ? Samagotchi::
|
|
715
|
+
current = File.file?(asset.path) ? Samagotchi::InstalledBundles::Sha.of_file(asset.path) : "(missing)"
|
|
712
716
|
edited = asset.edited? ? " (edited after install: the next install replaces it, a copy kept in the trash)" : ""
|
|
713
|
-
@stdout.puts "--- recorded sha256=#{Samagotchi::
|
|
717
|
+
@stdout.puts "--- recorded sha256=#{Samagotchi::InstalledBundles::Sha.recorded(asset.recorded)} current sha256=#{current}#{edited}"
|
|
714
718
|
end
|
|
715
719
|
|
|
716
720
|
# The base and the file; a marked one also the bundle's text it stays
|
|
@@ -779,7 +783,7 @@ module Samagotchi
|
|
|
779
783
|
"#{b.includes ? profile_members(b.includes, installed) : "files=#{b.files}"} installed=#{b.installed_at || "?"}"
|
|
780
784
|
line += " (shipped v#{b.upgrade.version}: chi bundle upgrade #{b.upgrade.source})" if b.upgrade
|
|
781
785
|
if b.behind&.any?
|
|
782
|
-
count = Samagotchi::
|
|
786
|
+
count = Samagotchi::InstalledBundles::FileStanding.behind_count(b.behind.size, unsure: b.behind.any?(&:unsure))
|
|
783
787
|
line += " (#{count}: chi bundle status #{b.name})"
|
|
784
788
|
end
|
|
785
789
|
@stdout.puts line
|
|
@@ -1068,7 +1072,7 @@ module Samagotchi
|
|
|
1068
1072
|
# A dev install is refused (it already follows its source), and a record
|
|
1069
1073
|
# whose source is relative, empty or gone says so. nil after such a
|
|
1070
1074
|
# refusal, written to stderr.
|
|
1071
|
-
# @return [Array(String,
|
|
1075
|
+
# @return [Array(String, InstalledBundles::Record, nil), nil] [the source, the
|
|
1072
1076
|
# record that named it (nil for a source as given)]
|
|
1073
1077
|
def upgrade_source(source)
|
|
1074
1078
|
normalizer = Samagotchi::MemoryBundle::SourceNormalizer
|