samagotchi 0.177.1 → 0.178.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +27 -1
  3. data/docs/cli.md +27 -5
  4. data/docs/guardrails.md +1 -1
  5. data/docs/internals/background-tasks.md +23 -2
  6. data/docs/internals/bridge.md +17 -6
  7. data/docs/internals/remote-sessions.md +6 -1
  8. data/docs/internals/session-lifecycle.md +17 -8
  9. data/docs/internals/web-frontend.md +7 -3
  10. data/docs/internals/working-set.md +31 -5
  11. data/docs/scheduling.md +8 -1
  12. data/docs/sessions.md +9 -5
  13. data/lib/samagotchi/bridge/card_store.rb +2 -19
  14. data/lib/samagotchi/bridge.rb +38 -6
  15. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  16. data/lib/samagotchi/compat.rb +0 -7
  17. data/lib/samagotchi/engine/events.rb +43 -0
  18. data/lib/samagotchi/engine.rb +9 -3
  19. data/lib/samagotchi/event_fanout.rb +56 -0
  20. data/lib/samagotchi/guardrails/approvals.rb +0 -4
  21. data/lib/samagotchi/schedules.rb +9 -4
  22. data/lib/samagotchi/session_access/contract.rb +4 -0
  23. data/lib/samagotchi/session_access/local.rb +16 -4
  24. data/lib/samagotchi/session_access/remote.rb +42 -9
  25. data/lib/samagotchi/session_archive_command.rb +38 -10
  26. data/lib/samagotchi/session_chain/delete.rb +75 -25
  27. data/lib/samagotchi/session_delete_command.rb +33 -10
  28. data/lib/samagotchi/session_lifecycle/allowed.rb +12 -9
  29. data/lib/samagotchi/session_manager/lifecycle.rb +12 -26
  30. data/lib/samagotchi/session_manager/removal.rb +109 -25
  31. data/lib/samagotchi/session_manager/running_tasks.rb +334 -0
  32. data/lib/samagotchi/sessions_command.rb +1 -1
  33. data/lib/samagotchi/task_files.rb +37 -4
  34. data/lib/samagotchi/terminal_ui/attached_loop/exit_commands.rb +7 -1
  35. data/lib/samagotchi/terminal_ui/attached_loop.rb +1 -1
  36. data/lib/samagotchi/terminal_ui/local_link.rb +11 -3
  37. data/lib/samagotchi/tools/task_runtime.rb +25 -6
  38. data/lib/samagotchi/version.rb +1 -1
  39. data/lib/samagotchi/web/app.rb +5 -1
  40. data/lib/samagotchi/web/public/data.js +19 -7
  41. data/lib/samagotchi/web/public/delete_sheet.js +26 -7
  42. data/lib/samagotchi/web/public/running_tasks.js +73 -0
  43. data/lib/samagotchi/web/public/session_actions.js +57 -8
  44. data/lib/samagotchi/web/public/stop_sheet.js +3 -2
  45. data/lib/samagotchi/web/public/working_set.js +3 -28
  46. data/lib/samagotchi/web/public/working_set_view.js +5 -2
  47. data/lib/samagotchi/web/public/ws_item_sig.js +51 -0
  48. data/lib/samagotchi/web/public/ws_peek.js +23 -13
  49. data/lib/samagotchi/web/public/ws_reader.js +22 -12
  50. data/lib/samagotchi/web/public/ws_timeline.js +9 -6
  51. data/lib/samagotchi/web/session_control.rb +65 -16
  52. data/lib/samagotchi/web/working_set_routes.rb +29 -8
  53. data/lib/samagotchi/worker_link.rb +9 -1
  54. data/lib/samagotchi/working_set.rb +26 -0
  55. data/lib/samagotchi/working_set_command.rb +9 -6
  56. metadata +4 -1
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 4a5b330c47fac34a4e9fd4c2d602e4cbc0241fe42a953bba227b6526ef619e7b
4
- data.tar.gz: 4c9ae4e9df6279202aa9540984c70148ef1ea6d2e9898542cb219ab1980b6f14
3
+ metadata.gz: 221dc2bfb6cf6d9e8d839dd49e5740b1b7e05f1f0ca77d64987418c755f2d82e
4
+ data.tar.gz: c26aca5d929e616c3e402b323ddd850e20d4e9193a42ebfbbe7b2f4cf9d28b8b
5
5
  SHA512:
6
- metadata.gz: bc2236c6ee5a909b4cfef2b66ab813b1546b9c8fe432734aec2909f84703cbe3dba48491a0e1a02f115650c9252ce9d087ea9e1b8dba327b61e5b483a9541d47
7
- data.tar.gz: a5b1653706fd962459dd639a4487d45bb28e96cdf3e022148d3fe4ce19967c84dd5a911d2f9014ad778c75945dfb0194b5c682549dd5fb39ec0c4886b3c0f65d
6
+ metadata.gz: 5d9caf39334981e0dbbe2417615f0db3e4c3e8a9fd8afc1e8caf63fb2de8bae2062c1ed11ef0de73145ec3aadbaee055a133e9f369eb915852fbd4d3fa9aed7d
7
+ data.tar.gz: 4d646ee36fbbc7880235793216ae4e5f975e5f77b794b1d39f25c7f1576eafc1388a48cc9d82fafce9386ffc45e483d4bf3c8ca73bfaac077a63f4b7dcaaf443
data/CHANGELOG.md CHANGED
@@ -8,6 +8,31 @@ and commands may change between minor versions. How releases are made:
8
8
 
9
9
  ## [Unreleased]
10
10
 
11
+ ## [0.178.0] - 2026-11-20
12
+
13
+ ### Changed
14
+
15
+ - Deleting or archiving a session whose background tasks still run now asks first: the web names them and offers to
16
+ stop them and delete/archive; `chi sessions delete|archive` (and `/archive`, `/exit --delete`) refuse and name them,
17
+ and `--stop-tasks` stops them first. With `--remote` this needs this chi on both ends: an older chi web can't stop
18
+ them, an older CLI can't delete or archive such a session there.
19
+ - chi no longer reads a guardrail approvals.json list written by chi 0.166 and before (set aside with a warning; allow
20
+ again what you need), or a session's cards.json from before 0.151.0 (earlier cards don't show).
21
+
22
+ ### Fixed
23
+
24
+ - `chi sessions restart` no longer refuses its fallback for a background task that already ended (a record a crashed
25
+ worker left marked running).
26
+ - A background task's leftover process holding its log is stopped even when chi exits just after the task's shell
27
+ ends, instead of running on after a one-shot or worker exit.
28
+ - chi web: the working set's peek and reader show a running turn's reads while it runs, not only once the turn has
29
+ ended; they ask again only when the open item changed.
30
+ - `chi sessions restart` (and the web's restart) of a session being deleted says "the session is being deleted"
31
+ instead of "its worker is still starting"; a schedule's skip says the same, and for a worker on a newer chi says
32
+ to restart chi web or update chi, instead of "its worker is starting or leaving".
33
+
34
+ Update with `chi update`.
35
+
11
36
  ## [0.177.1] - 2026-11-19
12
37
 
13
38
  ### Fixed
@@ -6496,7 +6521,8 @@ and long-lived sessions.
6496
6521
  - A macOS desktop helper (`chi desktop install`): a "Send to chi" Service and a
6497
6522
  hotkey panel that send selected text or the clipboard to your sessions.
6498
6523
 
6499
- [Unreleased]: https://github.com/dm1try/samagotchi/compare/v0.177.1...HEAD
6524
+ [Unreleased]: https://github.com/dm1try/samagotchi/compare/v0.178.0...HEAD
6525
+ [0.178.0]: https://github.com/dm1try/samagotchi/compare/v0.177.1...v0.178.0
6500
6526
  [0.177.1]: https://github.com/dm1try/samagotchi/compare/v0.177.0...v0.177.1
6501
6527
  [0.177.0]: https://github.com/dm1try/samagotchi/compare/v0.176.0...v0.177.0
6502
6528
  [0.176.0]: https://github.com/dm1try/samagotchi/compare/v0.175.0...v0.176.0
data/docs/cli.md CHANGED
@@ -18,7 +18,7 @@
18
18
  - `chi web --web-markdown` / `--no-web-markdown` — opt in to, or opt out of, sanitized Markdown rendering for completed assistant messages, the stage's asking text and a resolved question card's reply (`web.markdown`, off by default; `--no-web-markdown` turns a config's `web.markdown: true` off for this run)
19
19
  - `chi web --no-web-working-set` — turns the stage view's working set off (on by default; `--web-working-set` turns a config's `web.working_set: false` back on): what each turn brought into the model's context, in the stage and under each finished turn; `?working_set=1|0` on the page URL overrides it (see [The working set](#the-working-set))
20
20
  - `chi web --web-stage-collapsed` / `--no-web-stage-collapsed` — every session's stage starts folded to its status row, or not (`web.stage_collapsed`, off by default); a session folded or unfolded by hand keeps its own fold in that browser
21
- - `chi sessions list|stop|restart|archive|unarchive|delete|prune|clean|stats` — manage persisted sessions; `list` shows this git project's, `list --scope=all` every one, a delegated session with `↳ <parent>`, `list --archived` the archived ones too (see [Sessions](sessions.md)); one line per session (`<id> <state> <ctx> <updated_at> <text> [flags] ↳ … ↪ …`) and one footer (`N session(s) (sort=… order=…)`, or the project note) for the plain list, the `--live`/`--cwd` text and `--remote`. `stats ID` prints a session's cost, tokens and progress, and its own settings (`--set`; a `settings:` line), from a live worker's `GET stats`, else its saved `analytics.json` (`--format json` one object, with `settings`), without running a model turn. A usage error (an unknown subcommand or flag, a flag missing its value, `stop`, `restart` or `delete` with no ids, a bad `list --format`, `--scope`, `--sort` or `--order`, a `--days`, `--keep` or `--limit` that isn't a whole number) exits 2; an unknown or refused session exits 1
21
+ - `chi sessions list|stop|restart|archive|unarchive|delete|prune|clean|stats` — manage persisted sessions; `list` shows this git project's, `list --scope=all` every one, a delegated session with `↳ <parent>`, `list --archived` the archived ones too (see [Sessions](sessions.md)); one line per session (`<id> <state> <ctx> <updated_at> <text> [flags] ↳ … ↪ …`) and one footer (`N session(s) (sort=… order=…)`, or the project note) for the plain list, the `--live`/`--cwd` text and `--remote`. `stats ID` prints a session's cost, tokens and progress, and its own settings (`--set`; a `settings:` line), from a live worker's `GET stats`, else its saved `analytics.json` (`--format json` one object, with `settings`), without running a model turn. A usage error (an unknown subcommand or flag, a flag missing its value, `stop`, `restart` or `delete` with no ids, `unarchive --stop-tasks`, a bad `list --format`, `--scope`, `--sort` or `--order`, a `--days`, `--keep` or `--limit` that isn't a whole number) exits 2; an unknown or refused session exits 1
22
22
  - `chi note [--source NAME] [-m TEXT] (ID|PREFIX)... | --all` — add a context note (TEXT or stdin) to sessions: background the model sees on its next turn; it starts no turn (see [Sessions: Context notes](sessions.md#context-notes))
23
23
  - `chi broadcast [-m TEXT] [--all] [--dry-run]`, `chi broadcast log [--last N] [--format json]`, `chi broadcast deliver BROADCAST_ID (ID|PREFIX)...` — share one piece of information (TEXT or stdin) with every session it may concern, as a context note from `broadcast` (see [Broadcast](broadcast.md))
24
24
  - `chi context <add|push|ls|show|refresh|rm|mute|unmute> …` — attach live external text to sessions (a command chi runs every so often, or text pushed in); the model gets a short note when it changes and reads it with `context_read`; `chi context add <URL>` attaches a GitHub PR with the github-pr bundle; `chi context push NAME -m TEXT` (the long form is `--message TEXT`) gives a `--push` source its new text, read from stdin when no `-m` is given (see [Attached context](context.md))
@@ -763,10 +763,16 @@ a delegate's follow-up or a reminder. The web archives from the info bar
763
763
  (`archive`, before `stop`); the `archived` toggle by the all-sessions search
764
764
  finds archived sessions. `/archive` in a terminal leaves the session and
765
765
  archives it (an empty session is discarded instead; `chi scratch` refuses
766
- it). See
766
+ it). A session whose background tasks (its `task_create` tasks, an `execute`
767
+ handed over at its limit, its delegates' too) still run is refused, naming
768
+ them (`ab12cd34 refused: background tasks it started are still running: npm
769
+ run dev (--stop-tasks stops them first)`, exit 1); `archive --stop-tasks`
770
+ stops them first (TERM, then KILL) and says so (`archived (stopped its
771
+ worker; stopped 1 background task)`). `/archive` says the same and names
772
+ `chi sessions archive --stop-tasks ID`; the web asks a second confirm. See
767
773
  [Sessions](sessions.md#archiving-a-session).
768
774
 
769
- `chi sessions delete [--force] [--chain] ID...` deletes sessions for good: the
775
+ `chi sessions delete [--force] [--chain] [--stop-tasks] ID...` deletes sessions for good: the
770
776
  session file and its whole directory (notes, images, queued input). Each id
771
777
  (or unique prefix) gets one line: `deleted`, or `refused` with the reason.
772
778
  Deleting a chain's newest link undoes its continue and says so (`… deleted;
@@ -778,10 +784,20 @@ schedule on the chain refuses it. See docs/sessions.md (Session chains →
778
784
  Deleting a link). A
779
785
  session whose worker runs is refused unless `--force` stops the worker first;
780
786
  one a `--non-interactive` run has is always refused ("in use by a one-turn chi
781
- --non-interactive run or an older chi's terminal; let it finish first"). Exit
787
+ --non-interactive run or an older chi's terminal; let it finish first"). A
788
+ session whose background tasks still run (its own, or a delegate's or link's
789
+ the delete takes) is refused, naming them (`refused: background tasks it
790
+ started are still running: npm run dev, rspec (--stop-tasks stops them
791
+ first)`); `--stop-tasks` stops them first and the line says so (`deleted
792
+ (stopped its worker; stopped 2 background tasks)`; one chi can't verify or
793
+ read is never signalled: `1 not stopped: task 3f9a2c1d (may still be
794
+ running)`). `--stop-tasks` is not `--force`: a live worker is still refused
795
+ without it. `/exit --delete` refuses the same way and names `chi sessions
796
+ delete --stop-tasks ID`. Exit
782
797
  status: 0 when all are gone, 1 when any was refused or unknown, 2 on a usage
783
798
  error. The Web UI deletes too: `delete` in the info bar, or the ✕ on a card in
784
- All sessions; it asks first and stops a live worker.
799
+ All sessions; it asks first and stops a live worker, and asks again, naming
800
+ them, when background tasks still run (OK stops them).
785
801
 
786
802
  `chi sessions stats ID [--format text|json]` prints a session's cost, tokens
787
803
  and progress without running a model turn — the same text `/stats` prints in
@@ -1653,6 +1669,12 @@ CHI_REMOTE=studio chi context push claude-outbox ab12 < answer.json
1653
1669
  answer ab12 --question q1 --option N`, `chi --remote studio send --wait …`),
1654
1670
  under `CHI_REMOTE` too, an attach as well (`chi --remote studio --attach
1655
1671
  ab12 shows it`, `sessions stop`'s `chi --remote studio --resume ab12`).
1672
+ - `sessions delete|archive --stop-tasks` needs a chi web there that lists the
1673
+ `stop_tasks` feature (`GET /api/info`); an older one is refused before
1674
+ anything is sent (update and restart chi web there), and without the flag
1675
+ an older one deletes or archives as it always did. A new chi web answers an
1676
+ older CLI's delete or archive of a session whose tasks run with 409
1677
+ `tasks_running`, which that CLI prints as a failure.
1656
1678
  - A remote that can't be reached names itself and why (`chi send: remote
1657
1679
  studio (http://192.168.1.29:4567): connection refused`, exit 1; with
1658
1680
  `--format json` an `error` object).
data/docs/guardrails.md CHANGED
@@ -121,7 +121,7 @@ looks in the store): an owner's ask uses every scope; a [participant's turn](#a-
121
121
  (`Verdict#fresh_ask`) uses none.
122
122
  The file is a versioned store (`{"version": 1, "approvals": [...]}`, `Approvals::FORMAT`); a write keeps its version,
123
123
  the keys this chi doesn't know and an entry with no `scope`. A bare list of entries, as chi 0.166 and before wrote it,
124
- is read and converted to a versioned store on the next write. Chi 0.165 and before set a versioned store aside, so restart their sessions
124
+ is now set aside like an unreadable file. Chi 0.165 and before set a versioned store aside, so restart their sessions
125
125
  (`chi sessions restart`); a downgrade to 0.165 or before moves the store to a recoverable `approvals.json.corrupt-*`.
126
126
  A file that doesn't parse, or a versioned store whose `approvals` isn't a list, is moved aside to
127
127
  `approvals.json.corrupt-<UTC time>` with one warning, and chi starts with no stored approvals (more asks, nothing lost).
@@ -20,9 +20,9 @@ load the process code, and does not (`spec/require_cycle_spec.rb`, the thin clie
20
20
 
21
21
  | Module | Holds | Read by |
22
22
  |---|---|---|
23
- | `Tools::TaskRuntime` (`tools/task_runtime.rb`) | the lifecycle: `create_task`, `adopt`, the waiter (`record_exit_status`, `waiter_for`), refresh, `stop_task`, `get_record`, `list_records`, `running_created_in`, the leftovers; all process state (`@waiters`, `@settle_lock`) | the task tools, `execute`, `Bridge`, `HoldStop`, `TaskWatch`, `TurnEndings`, `Worker` |
23
+ | `Tools::TaskRuntime` (`tools/task_runtime.rb`) | the lifecycle: `create_task`, `adopt`, the waiter (`record_exit_status`, `waiter_for`), refresh, `stop_task`, `get_record`, `list_records`, `running_created_in`, the leftovers; all process state (`@waiters`, `@settle_lock`) | the task tools, `execute`, `Bridge`, `HoldStop`, `TaskWatch`, `TurnEndings`, `Worker`, `SessionManager::RunningTasks.stop!` (loaded at call time) |
24
24
  | `SpawnEnv` (`spawn_env.rb`) | the env a spawned command gets: `sanitized_spawn_env`, `spawn_env_for` (task_create's `env` checks), `SANITIZED_ENV_KEYS`, `MARKER_ENV_KEYS` | `execute`, `create_task`, `ProjectEnv.spawn_env` (required at call time: `child_env` requires `project_env`) |
25
- | `TaskFiles` (`task_files.rb`) | where a task's files are: `TASKS_DIR`, `METADATA_FILENAME`, `OUTPUT_FILENAME`, `EXIT_CODE_FILENAME`, `TASK_ID`, `metadata_path`, `task_dir_for`, `command_of` (a record read, no refresh) | `TaskRuntime`, `execute`, `ToolActivity`, `SessionManager`, `chi bundle try`'s sandbox, the slow-commands bundle |
25
+ | `TaskFiles` (`task_files.rb`) | where a task's files are: `TASKS_DIR`, `METADATA_FILENAME`, `OUTPUT_FILENAME`, `EXIT_CODE_FILENAME`, `TASK_ID`, `metadata_path`, `task_dir_for`, `tasks_dir`, `command_of` (a record read, no refresh), `with_root` (this thread's paths under another folder) | `TaskRuntime`, `execute`, `ToolActivity`, `SessionManager`, `chi bundle try`'s sandbox, the slow-commands bundle |
26
26
  | `TaskTranscript` (`task_transcript.rb`) | which tasks a conversation started, from its results' text: `created_ids_in`, `created_id`, `handed_over_id`, `RAN_AS_LINE` (matching on `ToolNames::Execute`) | `TaskRuntime.running_created_in`, `Bridge`, `TaskWatch`, `WorkerTaskWakes`, `SessionManager` |
27
27
 
28
28
  Behavior:
@@ -35,6 +35,27 @@ Behavior:
35
35
  - `execute` runs its command with stdout and stderr in two logs under `$XDG_STATE_HOME/samagotchi/execute/<id>/` (always an absolute path: a relative `XDG_STATE_HOME` is taken from the directory chi started in; outside the workspace: `git status` and `rm -rf tmp` never see them), stdin `/dev/null` and the same `exit_code` wrapper as a task. Its own copies of the logs hold a shared `flock` across the spawn: while a fresh exclusive `flock` fails, some process the command started still has them open. When the shell exits, a background child still holding them (`server &`) gets 1.5 s, then its group is stopped (the result's hint says to start a long job with `task_create` in the foreground, no `&`: a `cmd &` left behind there is stopped too); one holding none (`nohup server >log 2>&1 &`) is left alone. A holder that left the group (setsid) is out of the stop's reach: it runs on, the result ends with the "left running" hint, which says chi can't stop it and to kill it if it shouldn't run, and its dir stays for it to write to (the sweep removes it once no one holds the logs). Otherwise a finished command's dir is removed. Known gap on Linux: a command that writes through `/dev/stdout` or `/dev/stderr` (`echo b >/dev/stdout`) reopens the log file itself with `O_TRUNC`, so the output before it is lost (macOS dups the descriptor; the fix would be a relay pipe). The check needs the state dir on a local file system: over NFS, `flock` is emulated with `fcntl` locks, which children don't inherit.
36
36
  - The exit code: the command runs after an EXIT trap that writes the shell's status to the `exit_code` file (`TaskRuntime.wrapped_shell_command`, shared with `task_create`), so `exit N`, a `set -e` failure and a trailing `\` or `|` in the command all record what the shell exited with. The trap runs wherever the shell is when it exits (a `task_create` `cwd`, or a `cd` in the command), so `task_create`'s `exit_code_path` is absolute; its `output_path` stays relative (`tmp/tasks/<id>/output.log`, opened by chi in the worker's cwd before the spawn). A command that sets its own EXIT trap replaces it, and a shell killed by a signal skips it (zsh's sh mode, on TERM, INT and KILL): `execute` still reports the shell's status, and a `task_create` task or a handed-over execute gets its code from chi's waiter while the chi that started it runs (`TaskRuntime.record_exit_status`): the exit status, or `128 + the signal` (TERM → 143), with no new `stop_reason`. A record a refresh already finished without a code in between (`failed`, `process_ended_without_exit_code` or the not-chi's-process reason) is corrected, its `finished_at` kept; a stopped task (its stop flag on disk) is never touched. `process_ended_without_exit_code` is left only when the shell wrote nothing and the chi that started it was gone too.
37
37
  - `task_create` applies `execute`'s leftover rule (`Tools::Leftovers`, one implementation: `held?`, the grace, the group stop, the hint wording): `create_task` holds `output.log` with a shared `flock` across the spawn, and a handed-over execute's two logs are already held. When the task's shell exits and a process it started still holds the log (`yes >/dev/null &` with no `wait`), the task stays `running` (so the finish wake's watch and `task_wait` keep waiting) while the waiter of the chi that started it (`TaskRuntime.record_exit_status`) gives it 1.5 s (`LEFTOVER_GRACE_SEC`), then stops the group (TERM, 1 s, KILL; `Leftovers.stop_group`, only while the group still has members: a pgid isn't reused while it has any) and finishes the record in one write: the shell's status and exit code (the leftovers don't make it a failure) and `leftovers: "stopped"`. A holder outside the group with the group empty (a setsid'd `cmd &`, or a backgrounded `timeout N cmd &`: GNU `timeout` without `--foreground` moves itself and its command to a group of its own) is signalled nothing: `leftovers: "detached"`, left running, and the hint says so (`task_stop` can't reach it: kill it if it shouldn't run). A process holding no log (`nohup cmd >f 2>&1 &`) is left alone. `task_get`, `task_wait` (so the finish note too) and `task_list` add the hint line (`Leftovers.task_hint`), ``(a background process kept the task's log open and was stopped; to keep one running, run it in the foreground or end the command with `wait`)`` (or `was left running`), built from the same `Leftovers.hint` as execute's. One settler per task: while that waiter thread lives (`TaskRuntime.waiter_for`, in memory, this process only), a refresh here only reads a held record. With no waiter here (the chi that started it is gone, a worker that exited mid-grace, or another process reading), the next refresh that finds the shell dead and the log held settles it itself: a second look after 0.05 s (two `held?` probes at once read each other as holders), then the stop with a 0.5 s TERM grace and 0.5 s KILL wait (only of a group that still had members at the first look; one gone by the stop with nothing holding the log records no `leftovers`), so that read blocks up to ~1 s plus a `ps`. With no later reader of that cwd's tasks the leftovers run on; records already finished (an older chi's) are never revisited, and an older chi's record (its log never `flock`'d) reads as not held and settles as before. A `task_stop` during the grace stops the group (`Leftovers.stop_group`) and the record ends `stopped` (its stop flag wins over the waiter's write; in one process the two writes share a lock). Cost: one non-blocking `flock` try per log at shell exit (~0.2 ms), the grace only when something holds the log; a refresh of a running record whose shell is dead adds one `flock` try, and one `ps` only when the log is held.
38
+ - On a clean exit (worker teardown or a one-shot), `Engine#shutdown` calls `TaskRuntime.settle_pending!`: this process's
39
+ waiters whose shells are already reaped get time to finish their leftover grace and stop before chi exits. The wait
40
+ shares one deadline with the anytime-command joins (the later of their 3 s and ~4 s), and logs a warning if a selected waiter
41
+ remains. A shell still running at the snapshot, including one that exits during the join, is not waited on; a crash
42
+ or SIGKILL cannot wait either. With no later reader of that cwd, such leftovers can still run on.
43
+ - Nothing stops a running task when its worker leaves, so a user's delete or archive asks about the tasks the session
44
+ (and what the op takes with it) started: `SessionManager::RunningTasks` (`session_manager/running_tasks.rb`).
45
+ `.of(ids, state_dir:)` reads, per session, its file's transcript (`TaskTranscript.created_ids_in`) and each
46
+ `<working_directory>/tmp/tasks/<id>/task.json`, writing nothing and loading no `TaskRuntime`: a `Listing` of
47
+ `running` (the pid leads its group at the recorded `pid_started`), `unverified` (a group leader with no start time
48
+ to compare: none recorded, or none readable now) and `unreadable` (log `session_task_check_failed`). `Policy`
49
+ (`IGNORE`, the default; `REFUSE`; `Policy.stop(by:)` with its `Tally`) is the op's `running_tasks:`; restart's
50
+ fallback holds on a non-empty listing too. `.stop!` signals only `running` entries, one thread each, each running
51
+ `TaskRuntime.stop_task(id, by:)` inside `TaskFiles.with_root(root)`, all joined against one deadline
52
+ (`STOP_GRACE_SEC + ProcessGroup::KILL_WAIT_SEC + 0.5`); outcomes `stopped`, `ended`, `failed`, `unconfirmed` (and
53
+ the never-signalled `unverified`/`unreadable`) go into the tally, no command text logged.
54
+ `TaskFiles.with_root` sets a thread-local root that `metadata_path`, `task_dir_for`, `tasks_dir`,
55
+ `ensure_tasks_dir`, `list_records`' glob and `log_paths` (a relative `output_path` joined at read, stored unchanged)
56
+ read, so chi web and the CLI run `stop_task` from their own cwd; without a root every path is the relative one. A
57
+ thread the block starts doesn't inherit it (only `create_task` starts waiters, and nothing calls it under a root).
58
+ See [sessions.md](../sessions.md) (Deleting a session).
38
59
  - A stop of an `execute` (the user's Stop, the limit in kill mode) is done once the shell is reaped and nothing holds the logs: a child that ignores TERM after its shell died gets the KILL.
39
60
  - A command still running at `execute.timeout_sec` is handed over as a task (`execute.on_timeout: task`, the default; `kill` stops it instead, and the `!cmd` bang always kills): the result starts `Still running at the 120s limit: moved to a background task, not killed.`, then `task_id: …` and the tails of both logs so far. A command is also handed over early when a person's message waits for the turn's next step (the `message_waiting:` probe, the same `Engine#input_waiting?` as `task_wait`'s): after `Execute::EARLY_HAND_OVER_FLOOR_SEC` (3 s: a short command ends first and its result is the better answer), in the next 0.2 s slice. The first line then reads `Still running at the 4s mark: a message from the user is waiting, so the command moved to a background task, not killed.` (the seconds it had run), and the line after `task_id:` starts `Read the message first.`; the rest is the same hand-over, and the task stays watched. Never in `kill` mode (`execute.on_timeout: kill`, a participant's pair turn, the `!cmd` bang): there the probe is not even read and the command runs to its limit and is killed. A command that can't be adopted at that moment (a record that can't be written) isn't killed early: it runs on to its limit. Everything that matches the first line builds on `Execute::HANDED_OVER` (`Still running at the`) and `Execute::HANDED_OVER_AFTER` (both defined in `ToolNames::Execute`) (`120s limit:` or `4s mark:`): `TaskTranscript.handed_over_id`, `ToolActivity::HANDED_OVER_START`, `TaskWatch` (`limit_sec` for the limit's form, `early_sec` for the mark's, which the finish note words as `handed over by execute after 4s: a message from the user was waiting`) and the web's `task_stop.js`; the slow-commands bundle reads only the limit's form, which is the only one that is a timeout. A timeout during the 1.5 s background grace is a kill (the shell is gone, nothing to hand over). If the record can't be written, the command is killed. `TaskRuntime.adopt` writes a record for the process execute already started, with `handed_over_by: "execute"`. Its logs stay where execute wrote them, so the record's paths are absolute: `output_path` (stdout), `stderr_path` (stderr, a log of its own) and `exit_code_path` (a `task_create` record's `exit_code_path` is absolute too; its `output_path` is relative). `started_at` (and `created_at`) is the spawn time, not the hand-over's; `pid_started` is read at the hand-over, while execute's detach waiter is still running. From there it is an ordinary task: `task_wait`, `task_get`, `task_list` and `task_stop` treat it as any other. Its dir gets a `task` back-pointer file holding the record's absolute path. Once per process, the first `execute` sweeps `…/execute/`: a dir whose logs no process holds is removed when it has no back-pointer and is a day old (chi died mid-command), when its record is gone, or when it is 14 days old. The records live in each project's `tmp/tasks`, which the state dir can't list: hence the back-pointer.
40
61
  - `task_wait` and `task_get` show `stderr_path` when the record has one; `task_wait`'s output tail is followed by a `stderr_tail:` of at most 10 lines when that log isn't empty. A `task_create` task has one log (stdout and stderr together) and no `stderr_path`. A `task_wait` result longer than `max_tool_output_chars` keeps its header and the tail's end, with a gap line naming `output_path`, where the whole log already is (and `stderr_path`, when the record has one) (`ToolOutputCut`'s `:head_tail_ref`; nothing is copied; see [Tool output guardrails](tool-output-limits.md#the-runners-cut-max_tool_output_chars)).
@@ -209,8 +209,9 @@ the "asking again" and steer-cut rows, ✂ rows and questions (with how they wer
209
209
  so the stamp and the count always name one place, and the page finds it by the bubble (`card_stamps.js`: `data-turn-id`, or `data-opening-id` on a wake's note or a reason line), not by counting
210
210
  bubbles. An entry shown after reason lines also saves which one it came after (`after_opening`, beside `past_idless`): read
211
211
  first while that line is still in the run, so a later release can drop the count. No stamp (the page counts `turns_since`) for
212
- an entry before every opening, after a line an older chi wrote with no id, or from a version 1 file (`base_since`). A rollback
213
- keeps today's rule: a rolled-back turn's cards name the opening before it.
212
+ an entry before every opening or after a line an older chi wrote with no id. A version 1 file is no longer read (its earlier
213
+ cards do not show); `base_since` remains readable in version 2 files saved since. A rollback keeps today's rule: a rolled-back
214
+ turn's cards name the opening before it.
214
215
  The saved recap carries the same stamp: `saved_recap`'s `opening_id` (`RecapPlace.opening_id`, the id of the last
215
216
  opening its `covered` messages hold, read at read time, so `recap.json` is unchanged), which the page places it after
216
217
  (`recap_stamp.js`); an older worker's `saved_recap` has none, and the page counts `turns_since`.
@@ -237,9 +238,8 @@ the "asking again" and steer-cut rows, ✂ rows and questions (with how they wer
237
238
  are the worker's own (each start announces them) and an unanswered question waits for no one: neither is saved or seeded. An
238
239
  entry from an earlier worker lists with `earlier: true`; one shown during a turn comes back **without its actions** (their
239
240
  turn no longer runs), while a between-turns card keeps its buttons.
240
- - **Version 1.** A file from before the log (top-level `turns`, each entry its own, maybe `running`) keeps its places, drift
241
- included: `seed` turns each count into `base_since`, new openings add to it, and such an entry never reads as having left
242
- nothing (no id to check). The next save writes version 2 with `base_since` kept. `SessionManager.cards_empty?` reads both.
241
+ - **Version 1.** A file from before the log (top-level `turns`, each entry its own, maybe `running`) is no longer read, so its
242
+ earlier cards do not show. `SessionManager.cards_empty?` still reads both versions to decide whether a session is empty.
243
243
  - **An older chi on a version 2 file.** Its `seed` wants an integer `turns`, finds none, and starts with no entries. A chi web not
244
244
  yet restarted only reads: it lists no cards for that session until restarted, and the file stays whole. An older **writer** does
245
245
  damage: at its first saved event, `:turn_started`, it writes `{"version":1,"turns":0,"running":true,"entries":[]}` over the file
@@ -488,7 +488,17 @@ The Bridge exposes:
488
488
  `cards` (`CardStore#list`; a card an earlier worker showed during a turn comes back read-only, with no
489
489
  actions: its turn no longer runs), `event_seq`, `event_id`, all taken in one event-log hold; no message
490
490
  list, so it costs the same however long the session is. `?turn_id=` answers that turn's answer
491
- (an unknown or missing id: the newest); the only route that reads its query.
491
+ (an unknown or missing id: the newest). A handler in `Bridge::QUERY_HANDLERS` gets the query string; no other one does.
492
+ - `GET /session/:id/working_set/item?kind=&key=[&now=1][&latest=1]` — what the model has of one working-set item
493
+ (`Engine#working_set_item`: `WorkingSet.timeline_of`'s `{kind, key, events}`, `now:` for a memory with `now=1`;
494
+ with `latest=1` only the peek's events and `counts`, `WorkingSet::Timeline#peek_h`), plus
495
+ `at` (the conversation's size it was built from) and `running`. While a turn runs it reads the turn's view
496
+ (`EventFanout#turn_view`: a shallow copy of the running turn's conversation taken at each `:generation_started`,
497
+ used only while that turn's id is the running one, dropped at the turn's end under the event lock), else a copy of
498
+ the session's messages. `400 invalid_item`
499
+ (`WorkingSet::INVALID_ITEM`, chi web's words) for a kind it doesn't know or a blank key. Owner-only is chi web's
500
+ (its route is `:owner`); the Bridge's gate is its secret. Advertised as `working_set_item`
501
+ ([working-set.md](working-set.md#delivery)).
492
502
  - No browser: only chi's own clients talk to a Bridge. A request with an `Origin` header, a `Sec-Fetch-Site`
493
503
  other than `none`, or a `Host` that isn't loopback (a DNS-rebound page) is `403 cross_origin`
494
504
  (`Bridge#browser_request?`, before any route); there is no CORS and no `OPTIONS` route. The browser reaches a
@@ -647,6 +657,7 @@ compatibility from its version. `Bridge::FEATURES` advertises:
647
657
  | `cancel_turn_id` | `POST /session/:id/cancel` can stop only the named turn. |
648
658
  | `participant_revise` | chi web can pass a participant's Revise draft for worker-side validation. |
649
659
  | `participant_client_id` | chi web can identify a participant as `participant:<id>` instead of using the legacy `review:<id>`. |
660
+ | `working_set_item` | `GET /session/:id/working_set/item` answers one item's timeline (the running turn's mid-turn), so chi web asks for it instead of the whole snapshot. |
650
661
 
651
662
  `chi web`'s `GET /api/sessions/:id/stream` proxies this bridge
652
663
  (503 `not_live` for no worker, a leaving or stuck worker, or an unreachable Bridge; 502 `worker_newer` for skew and
@@ -133,7 +133,12 @@ the session commands*. Keep that table in step with `SessionAccessRoutes`.
133
133
  `ArgumentError` for another `not_found`, `Session::AmbiguousId`,
134
134
  `SessionManager::OwnedByTUI` / `DeleteRefused` / `ArchiveRefused` / `RestartRefused`, `SessionContinue::Refused`,
135
135
  and `ModelProfile::MissingModel` for `invalid_model` (no model there, or `--model`'s host unknown there: "could not
136
- start a session: …", exit 1, as here).
136
+ start a session: …", exit 1, as here). A delete's or archive's `409 tasks_running` carries `op` (`delete` or
137
+ `archive`), `tasks` (`{running, unverified, unreadable}`), `worker_stopped`, `stopped_worker` (whose; an older chi web sends only the Boolean) and a chain's `links`: `raise_refusal`
138
+ rebuilds `DeleteRefused` or `ArchiveRefused` by `op`, with the `RunningTasks::Listing`, and makes the words here
139
+ (`RunningTasks.words`), not from chi web's `message`. Its own code, not archive's `busy`: an older client prints
140
+ `RemoteFailed "… answered 409 tasks_running: …"` rather than "a turn is running". `--stop-tasks` asks for the
141
+ `stop_tasks` feature first (`RemoteTooOld` without it).
137
142
  Checks the client would make locally come back as `SessionAccess::Refused` (`parent_answers_refused`,
138
143
  `parent_continue_refused`, `no_vision`, exit 1) or `BadRequest` (the other `invalid_*`, `missing_fields`, `bad_images`,
139
144
  exit 2, the usage-error path). That is for the routes `raise_refusal` reads (create, uploads, …). `POST …/turn` is
@@ -41,9 +41,9 @@ These are reader labels, not stored values:
41
41
  |---|---|
42
42
  | `absent` | No session file; a leftover sidecar directory may still exist (its facts are ignored). |
43
43
  | `tui_owned` | `owner.lock` held with kind `tui` (a one-shot `chi -p --non-interactive` owns it): an in-process one-turn host, not a worker. Wins over a stop, a start, an archive. |
44
- | `deleting` | `owner.lock` held with kind `deleting` while the session's files go (`WorkerLink` reads it as `Starting`). Every delivery is refused (`WakePolicy`'s `:deleting`). |
44
+ | `deleting` | `owner.lock` held with kind `deleting` while the session's files go (`WorkerLink` reads it as `Starting`). Every delivery is refused (`WakePolicy`'s `:deleting`); restart refuses it (`deleting`); a schedule skips it ("the session is being deleted"). |
45
45
  | `stopping` | A worker holds the lock and the `stopped` marker exists, whatever its link. |
46
- | `skew` | A worker holds the lock and its sidecar speaks a newer protocol (`WorkerLink::Skew`). |
46
+ | `skew` | A worker holds the lock and its sidecar speaks a newer protocol (`WorkerLink::Skew`); a schedule skips it with Skew's short words. |
47
47
  | `leaving` | The worker closed its Bridge and still holds the lock (`leaving_at`, `WorkerLink::Leaving`). |
48
48
  | `booting_stuck` | A worker has held the lock past `WorkerLink::START_LIMIT` without its sidecar (`Starting`, stuck). |
49
49
  | `booting` | A worker holds the lock without its matching sidecar yet (`Starting`); also an owner of unknown kind (a lock record still blank after `OWNER_READ_ATTEMPTS`). |
@@ -88,16 +88,21 @@ state. A cell is `:go`, `:wait` or the decider's own refusal reason; `SessionLif
88
88
  - **Literal columns** (`LITERAL`): resume (`resume_session`), restart (`restart_session`: `stop_marked` in every
89
89
  state with the stop marked: stopping, stopped, stopped_starting), stop (`stop_session`),
90
90
  archive (`archivable!`), delete (`release_for_delete!`, without a stop), sched_chain and sched_same
91
- (`Schedules#busy_reason`; `worker_busy` is "its worker is starting or leaving") and attach
91
+ (`Schedules#busy_reason`; `worker_busy` is "its worker is starting or leaving", `deleting` the delivery's "the
92
+ session is being deleted", `worker_newer` `WorkerLink::Skew#short_message`) and attach
92
93
  (`TerminalUI::LocalLink#live_worker`: `gone_stopped`, `gone_worker_newer`). They assume neutral op-local facts: not
93
94
  scratch, saved status idle, no `input/`, no question or offer, not SIGSTOPped, features restart and activity, an idle
94
95
  worker with no streams. Absent's delete and schedule cells are unreachable (a gone session is refused first).
95
96
 
96
97
  Link resolution (`SessionInbox::Head.resolve`, `Schedules#target_of`) stays outside: the cells are the link's own.
97
98
 
99
+ The running-tasks check of a user's delete and archive (`SessionManager::RunningTasks`, `tasks_running`) is op-local,
100
+ not an `ALLOWED` cell: it reads the transcript and each `task.json`, not the lifecycle's facts, and runs after the
101
+ lifecycle refusals (`refuse_scheduled!`, `archivable!`), before the worker is stopped.
102
+
98
103
  `restart_session` is the first decider migrated to the table: its lifecycle precheck is `SessionLifecycle.read` (the
99
104
  owner read through `session_owner`) and `ALLOWED[:restart]`: `owned_by_tui` raises `OwnedByTUI`, a refusal cell
100
- raises `RestartRefused` with it as the reason (`starting`, `not_running`, `stop_marked`), `fallback` goes to
105
+ raises `RestartRefused` with it as the reason (`starting`, `not_running`, `stop_marked`, `deleting`), `fallback` goes to
101
106
  `restart_fallback` (skew, a stuck start) and `go` asks the live worker. Its op-local checks stay where they were: the
102
107
  SIGSTOP check (`:stopped`, the worker's pid: a different condition with its own words, before the table's refusal),
103
108
  the worker's `restart` feature, the Bridge's reply and the fallback's holds. The matrix still drives it, so its
@@ -118,11 +123,13 @@ code can't make (a one-turn run's lock with a stop) is marked `reachable: false`
118
123
  Every answer must equal `ALLOWED[op][state]` (for the session hub, `SHOWN[state]`: `Web::SessionSummary.build`'s
119
124
  status and bridge_up, its `SessionRow`'s live), or be named by exactly one `KNOWN_DIFFERENCES` entry (op, a `when`
120
125
  over the row, a plain reason); an entry that names no mismatch fails as stale. The entries are the findings for the
121
- owner, not fixed: stop-first schedule and attach checks under a one-turn run's, a deleter's or an unknown owner's lock;
122
- chain mode's starting check before any one-turn-run check; a start marked after the stop holding a resume off;
126
+ owner, not fixed: stop-first schedule checks under a one-turn run's or an unknown owner's lock, and attach's under a
127
+ one-turn run's, a deleter's or an unknown owner's; chain mode's starting check before any one-turn-run check; a start
128
+ marked after the stop holding a resume off;
123
129
  `wake_for_report` reporting a worker's `:live` as `:owned`; the hub's bridge_up, live and status overlay. (Restart
124
- never reading the stop and `busy_reason`'s live branch falling through to the starting check were fixed: their
125
- entries went stale and were removed.) The delivery columns are
130
+ never reading the stop, the restart and schedule reading a deleter as starting, the schedule's Skew words, and
131
+ `busy_reason`'s live branch falling through to the starting check were fixed: their entries went stale and were
132
+ removed.) The delivery columns are
126
133
  generated from `WakePolicy::ROWS`, so for deliveries the matrix proves the states are drawn right (decide is a function
127
134
  of the state), not what WakePolicy does; the literal columns and `SHOWN` are goldens.
128
135
 
@@ -151,6 +158,8 @@ These are documented race boundaries, not promises of an atomic lifecycle transi
151
158
  | Stop reads an owner pid, then sends TERM. | `LifecyclePart#stop_session` (`session_manager/lifecycle.rb`): the pid can be reused between the owner read and `Process.kill`; protecting that requires a real pid-reuse scenario. | No unit pin: pid reuse/process signaling is not reliably representable without real processes. |
152
159
  | Saved `status` is used as a lifecycle hint. | `LifecyclePart#restart_fallback_holds` and `RemovalPart#archive_refusal` (`session_manager/lifecycle.rb`, `session_manager/removal.rb`) use saved `running` status as a busy hint; status is not a lock or proof that a worker is alive. | Unit spec: pin fallback refusal from saved status without a live Bridge. |
153
160
  | Stop/start ordering depends on wall-clock `at`. | `SpawnPart#claim_start` and `StartingMarker#claim` (`session_manager/spawn.rb`, `starting_marker.rb`) compare `starting.at` with `Session.stopped_at`; same-time starts are treated as before the stop. Clock adjustments across processes are not serialized. | Unit spec: pin the inclusive `at <= over_before` takeover boundary. |
161
+ | A delete stops a session's background tasks. | `RemovalPart#remove_session_files` (`session_manager/removal.rb`): with `running_tasks:` a stop, `RunningTasks.stop!` runs under the DELETING owner lock, after the `StartingMarker.fresh?` re-check and `still`, for up to ~4 s; meanwhile a send, a schedule or a resume is refused as deleting. With `REFUSE` the same seat lists the final file again and refuses a task started since the op's check (`worker_stopped` set when the op stopped the worker; `stopped_worker` names whose). `SessionChain::Delete` lists a whole batch (a link and its D7 delegates) once under the batch's locks, before any of it goes (`refuse_tasks!`), and its removals then skip the per-id re-check (`RunningTasks.after_check`), so no refusal comes after part of the batch went. A chain with `--stop-tasks` stops link by link inside each `locked(batch)`, serially: up to ~4.5 s per link, N links N times that, with that batch's locks held; a link refused part-way keeps its tasks running. A stop that outlives the join's deadline (`unconfirmed`) is reported as not stopped and may still finish after the files are gone (its thread goes on writing the record under the session's working directory, not the session dir). | `removal_spec.rb` (a worker's `OwnerLock.acquire` during the stop fails; the re-check refuses a new task), `session_chain/delete_spec.rb` (link by link, part-way; a task started after the up-front check keeps the link, its delegate and the chain whole). |
162
+ | An archive stops a session's background tasks without a lock. | `RemovalPart#archive_session`: the stop runs after the tree's workers were stopped and waited for (`stop_session(wait:)`), before the marker; a worker that outlives the wait records the stop itself from the `stop_requested_by` flag on disk (`record_exit_status` / `correct_finished_record`). A task started after the listing isn't stopped: archive already refuses `busy` up front. | `removal_spec.rb` (the stop sees no owner left). |
154
163
  | Several methods write or remove the same marker. | The definitions/callers in `session.rb`, `starting_marker.rb`, `archive_store.rb`, `bridge.rb`, and `reminder_carry.rb` are the source of truth; these APIs have multiple call sites. | `spec/session_lifecycle_writers_spec.rb` pins the call-site allow-lists; it does not claim their operations are one transaction. |
155
164
 
156
165
  ## Adding a transition
@@ -31,7 +31,7 @@ page. A factory dep a new version stops passing is the same hazard the other way
31
31
  out of `send_turn.js`, `session_actions.js` and `lists_view.js`); a page loaded before keeps all its old modules
32
32
  until a reload, so the risk is a mixed cache, not an open tab. `answer_fold.js`, `details_motion.js`,
33
33
  `turn_range.js`, `history_reveal.js`, `latest.js`, `session_payload.js`, `method_api.js`, `session_store.js`,
34
- `session_fields.js`, `feature_gates.js`, `revise_stack.js`, `revise_switch.js`, `shell_command.js`, `stale_params.js`, `popover_modal.js`, `more_sheet.js`, `delete_sheet.js` (Deleting a chained session, below), `hash_intent.js` (what the hash asks for: session, all, start or keep), `worker_features.js`, `version_notices.js`, `owner_claim.js`, `owner_verify.js`, `composer_mode.js`, `strip_hidden.js`, `block_open.js`, `text_roots.js`, `block_source.js`, `block_frame.js`, `block_host.js`, `block_watch.js`, `card_stamps.js`, `recap_stamp.js` (a saved recap's place by its `opening_id` stamp, else its count), `inline_widgets.js`, `widget_walk.js`, `widget_picks.js`, `history_shape.js` (the history's shape, live against a reload: the e2e reload checks and the opt-in reload check share its normalizer and its `ACCEPTED` allowlist), `turn_pieces.js` (a finished turn's one order and its answer rule: the live hand-off's `handOffOrder` and `turnEnded`, and a reload's `turnHistoryNodes`), `reload_check.js` (the opt-in `web.reload_check`: after the stage's hand-off, the turn against a reload of it, the counts posted; the history without its cards and questions, and those as data: the page's `card_registry.js` against one seeded from the read, this turn's entries, a capped read's missing keys skipped), `turn_drawing.js` (a finished turn's drawing, `turn_drawings` in the show: its fold into steps and its end kind; `turn_block.js` draws it), `stage_stall.js` (the stage's quiet signal), `stage_quiet_clock.js`, `stage_dom.js`, `stage_answer.js`, `stage_pager.js`, `stage_cloud.js`, `stage_handoff.js`, `stage_place.js`, `stage_probe.js` (the stage's features: below, The stage's modules), `card_kinds.js` (what a card waits as, from its data: the kind, approval and folded-row text the stage's registry takes; the node's read is its cross-check), `card_registry.js` (the open session's cards as data, an observer of the stream's card events and a read's seed: Where state lives), `history_end.js` (the stage's one move of pieces to the history's end), `stage_opened.js` (a running turn opened in the history while a card waits: the lead-in bubble, the moves, the end fold), `stage_asking.js` (the stage's docked card and its fold: the docking and lead-in rules, the opening, a waiting card's own toggle, the folded row's text per kind, the fold's choice, reveal and the docked card's fold; `stage_view.js` wires it), `stage_waiting.js` (the stage's waiting cards as data, keyed by `data-qid` / `data-card-id`: kind, docked, approval, the stage's order, the shown card and its pager, the docked card's fold, kept for this tab in `chi_asking_fold:<session>`; `front`, `count`, `shown`, `blocking`), `stage_cards.js` (the cards that wait in the stage: `PENDING`, `ASKS`, `waitsInStage`, read by `stage_model.js placeKind`), `resync_reach.js` (a re-read that can't reach chi web keeps the drawn history; the status chip says retrying / offline, outside a turn), `session_sync.js` (the open session's sync: `select`, `resync` and its retries, the stream's life; the stream handle and the re-read bookkeeping are its own), `session_view.js` (the open session's view: `renderSessionView` draws a read, `forgetSession` resets the page for another session, `readTurnEnd`, `endTurnView`; app.js makes both right after the cards, each reaching the other and the later views through getters), `participant_main.js`, `participant_bar.js`, `viewer_self.js`, `participant_history.js` (a participant's ↑/↓ list), `stage_owner_wait.js`, `participant_revise.js` (a participant's page: The participant's page, below), `ws_timeline.js`, `ws_cards.js`, `ws_peek.js`, `ws_reader.js`, `ws_way_in.js` (what chi has of a working-set item: below, The working set's reader), `session_prefs.js` (a session's own view settings, `<key>:<session>`: Storage keys, below), `ws_sections.js` (the working set's head view: its sections from the prompt's parts, [working-set.md](working-set.md), The head view), `ctx_tokens.js` (the context's token count beside its %: `ctxTokens`, below), `stage_view_memory.js` (what was opened of a running turn, per session, in memory: Where state lives), `no_contact_fill.js` (a text field that isn't a contact form: autocomplete off and a name with no contact word, against iOS Safari's AutoFill Contact bar; a template's fields carry the same attributes, and its spec checks the page's markup for them) and the `objectives_*.js` modules are new modules for that reason. The last four `block_*` draw fenced blocks (`block_watch.js` finds and watches them, `block_host.js` is its frame drawer for a bundle's renderers): [block-renderers.md](block-renderers.md). `inline_widgets.js` is its core drawer for `chi-ui` blocks, drawing `widget_walk.js`'s and `widget_picks.js`'s widgets in a shadow root styled by `widgets.css`: [inline-widgets.md](inline-widgets.md).
34
+ `session_fields.js`, `feature_gates.js`, `revise_stack.js`, `revise_switch.js`, `shell_command.js`, `stale_params.js`, `popover_modal.js`, `more_sheet.js`, `delete_sheet.js` (Deleting a chained session, below), `running_tasks.js` (a delete's or archive's 409 `tasks_running`: the tasks' line, the second confirm, the toast's suffix; DOM-free, so `stop_sheet.js` and `delete_sheet.js` share its cut), `hash_intent.js` (what the hash asks for: session, all, start or keep), `worker_features.js`, `version_notices.js`, `owner_claim.js`, `owner_verify.js`, `composer_mode.js`, `strip_hidden.js`, `block_open.js`, `text_roots.js`, `block_source.js`, `block_frame.js`, `block_host.js`, `block_watch.js`, `card_stamps.js`, `recap_stamp.js` (a saved recap's place by its `opening_id` stamp, else its count), `inline_widgets.js`, `widget_walk.js`, `widget_picks.js`, `history_shape.js` (the history's shape, live against a reload: the e2e reload checks and the opt-in reload check share its normalizer and its `ACCEPTED` allowlist), `turn_pieces.js` (a finished turn's one order and its answer rule: the live hand-off's `handOffOrder` and `turnEnded`, and a reload's `turnHistoryNodes`), `reload_check.js` (the opt-in `web.reload_check`: after the stage's hand-off, the turn against a reload of it, the counts posted; the history without its cards and questions, and those as data: the page's `card_registry.js` against one seeded from the read, this turn's entries, a capped read's missing keys skipped), `turn_drawing.js` (a finished turn's drawing, `turn_drawings` in the show: its fold into steps and its end kind; `turn_block.js` draws it), `stage_stall.js` (the stage's quiet signal), `stage_quiet_clock.js`, `stage_dom.js`, `stage_answer.js`, `stage_pager.js`, `stage_cloud.js`, `stage_handoff.js`, `stage_place.js`, `stage_probe.js` (the stage's features: below, The stage's modules), `card_kinds.js` (what a card waits as, from its data: the kind, approval and folded-row text the stage's registry takes; the node's read is its cross-check), `card_registry.js` (the open session's cards as data, an observer of the stream's card events and a read's seed: Where state lives), `history_end.js` (the stage's one move of pieces to the history's end), `stage_opened.js` (a running turn opened in the history while a card waits: the lead-in bubble, the moves, the end fold), `stage_asking.js` (the stage's docked card and its fold: the docking and lead-in rules, the opening, a waiting card's own toggle, the folded row's text per kind, the fold's choice, reveal and the docked card's fold; `stage_view.js` wires it), `stage_waiting.js` (the stage's waiting cards as data, keyed by `data-qid` / `data-card-id`: kind, docked, approval, the stage's order, the shown card and its pager, the docked card's fold, kept for this tab in `chi_asking_fold:<session>`; `front`, `count`, `shown`, `blocking`), `stage_cards.js` (the cards that wait in the stage: `PENDING`, `ASKS`, `waitsInStage`, read by `stage_model.js placeKind`), `resync_reach.js` (a re-read that can't reach chi web keeps the drawn history; the status chip says retrying / offline, outside a turn), `session_sync.js` (the open session's sync: `select`, `resync` and its retries, the stream's life; the stream handle and the re-read bookkeeping are its own), `session_view.js` (the open session's view: `renderSessionView` draws a read, `forgetSession` resets the page for another session, `readTurnEnd`, `endTurnView`; app.js makes both right after the cards, each reaching the other and the later views through getters), `participant_main.js`, `participant_bar.js`, `viewer_self.js`, `participant_history.js` (a participant's ↑/↓ list), `stage_owner_wait.js`, `participant_revise.js` (a participant's page: The participant's page, below), `ws_timeline.js`, `ws_cards.js`, `ws_peek.js`, `ws_reader.js`, `ws_way_in.js`, `ws_item_sig.js` (what chi has of a working-set item: below, The working set's reader), `session_prefs.js` (a session's own view settings, `<key>:<session>`: Storage keys, below), `ws_sections.js` (the working set's head view: its sections from the prompt's parts, [working-set.md](working-set.md), The head view), `ctx_tokens.js` (the context's token count beside its %: `ctxTokens`, below), `stage_view_memory.js` (what was opened of a running turn, per session, in memory: Where state lives), `no_contact_fill.js` (a text field that isn't a contact form: autocomplete off and a name with no contact word, against iOS Safari's AutoFill Contact bar; a template's fields carry the same attributes, and its spec checks the page's markup for them) and the `objectives_*.js` modules are new modules for that reason. The last four `block_*` draw fenced blocks (`block_watch.js` finds and watches them, `block_host.js` is its frame drawer for a bundle's renderers): [block-renderers.md](block-renderers.md). `inline_widgets.js` is its core drawer for `chi-ui` blocks, drawing `widget_walk.js`'s and `widget_picks.js`'s widgets in a shadow root styled by `widgets.css`: [inline-widgets.md](inline-widgets.md).
35
35
 
36
36
  ## One page, every viewer
37
37
 
@@ -648,8 +648,12 @@ for the set, its jumps and its list, and `whatChiHas` for refs.js), `ws_way_in.j
648
648
  flag turn_html.js reads; on only once the reader is attached). State: the reader's own closure (the open item, its
649
649
  answer, the tab), never `store.current`. The reader is a `section` in `#center` over the history and the composer
650
650
  (both `inert` while it is open, so their scroll place stays; a phone's is `position: fixed`). Each item answer goes
651
- through `createLatest` keyed by the session and the item; a new server snapshot (`onServer`) asks again while it is
652
- open (the route's messages lag a running turn). Leaving the session closes it and the peek: `session_view.js
651
+ through `createLatest` keyed by the session and the item, and an answer older than the drawn one within one running
652
+ turn (same `turn_id`, lower `at`) is dropped (`ws_item_sig.js olderAnswer`); a new server snapshot (`onServer`, and the
653
+ peek's `refresh` on an event) asks again only when the open item's server signature changed (`ws_item_sig.js serverSig`:
654
+ its `count`, `ops`, `tokens`, `state`, `has_drop`, `pinned`; mid-turn the route answers the running turn's view as of
655
+ its last step). The peek asks `latest=1` (only the events `peekOf` picks, and `counts`), the reader the whole
656
+ timeline. Leaving the session closes it and the peek: `session_view.js
653
657
  forgetSession` (a switch, the start page, + New, a deleted or archived session) calls `wsPreview.reset()`, so
654
658
  `#center` is never left inert, whatever the next session's GET does; close gives focus back to where it was at the
655
659
  open (not after a jump or a reset). Styles: `ws_preview.css`.
@@ -161,9 +161,27 @@ Engine emits only a set that differs from the last one), and the GET builds from
161
161
  does one from an older worker without the field, its answer then behind the turn's events, which the page keeps.
162
162
 
163
163
  **An item's timeline while a turn runs** (`GET …/working_set/item`, [Timeline](#timeline-what-the-model-has-of-one-item))
164
- has no such event to answer: it always builds from the snapshot's messages, so mid-turn it lags the turn's runs
165
- (the running turn's reads of the item are not in it yet). Accepted for v1: the page asks again on each
166
- `:working_set_updated` while its reader or a peek is open, and the turn's end brings the messages up to date.
164
+ is the running turn's as of its last step, the moment the rows are from. At every `:generation_started`, on the turn's
165
+ thread and before the event goes out, `EventFanout#keep_turn_view` keeps a `TurnView`: a shallow copy of the running
166
+ turn's conversation (`conversation.map(&:dup)`, a new Array and each entry Hash dup'ed, strings shared), its size
167
+ (`at`), the set's strategy, the session's folder and the turn's id. Every step, not only when the set changed (an edit
168
+ or a forget changes what the model has without changing the rows). A copy, because the turn's thread writes entries in
169
+ place (`LLMContextEdit.store`'s `:edits`) while a Bridge thread reads; shallow is enough because every in-turn writer
170
+ changes top-level keys only (`LLMContextEdit.store`/`.remove`, the forget store, ChatLoop's `:interrupted`; KernelLoop
171
+ appends or pops; `spec/engine_working_set_spec.rb` pins it). Cost: about 0.02 ms and 32 KB for 200 entries, 0.03 ms and
172
+ 82 KB for 500, one copy kept. `EventFanout#turn_view` hands it out only while its turn id is the running turn's (the
173
+ guard `Engine#live_conversation` uses), so a view left from another turn is never read; `Engine#end_turn` also drops
174
+ it (`EventFanout#drop_turn_view`) under the event lock as it puts the kept messages in place, before its
175
+ `:working_set_updated` and before the turn has ended, so no answer in that gap is the running view. `Engine#working_set_view` is
176
+ the conversation the set is built from now (that view, else a copy of the session's messages: a starting turn shares
177
+ their entries and writes them in place), read by `Engine#working_set_item`
178
+ (the Bridge's `GET working_set/item`, feature `working_set_item`: chi web asks a worker with it for just the item and an
179
+ older worker for its snapshot, as the route below says) and by `/working-set`'s listing (mid-turn the copy holds the
180
+ sent note, so no op is pending). The answer carries `at`, `running` and, mid-turn, `turn_id`. The page asks again only
181
+ when the open item's server signature changed (its `count`, `ops`, `tokens`, `state`, `has_drop`, `pinned`; a re-read
182
+ raises `count`), at the peek's refresh on an event and the reader's `onServer`; it drops an answer with a lower `at`
183
+ only within one running turn (`at` can go down at a turn's end, which keeps less). The peek asks `latest=1`
184
+ (`Timeline#peek_h`: only the events `peekOf` picks and the per-op `counts`); the reader the whole timeline.
167
185
 
168
186
  ## Steering: drop and undrop
169
187
 
@@ -283,8 +301,16 @@ file is; nil without a stamp.
283
301
 
284
302
  **The route.** `GET /api/sessions/:id/working_set/item?kind=&key=` (`WorkingSetRoutes#handle_working_set_item`,
285
303
  `:owner, :session`: a participant gets 403 from `not_permitted_for`) answers `timeline.to_h`, and with `&now=1` for a
286
- memory `now:` too. Unlike the set's route it never answers a worker's precomputed set: it builds from
287
- `working_set_source` (the worker's snapshot messages, else the file's; the session's strategy and folder). Its texts
304
+ memory `now:` too. A live worker that advertises `working_set_item` (`WorkingSet::ITEM_FEATURE`,
305
+ `WorkerLink.live_features`) is asked for just the item: the Bridge's `GET working_set/item` (`Engine#working_set_item`,
306
+ the query encoded with `URI.encode_www_form`, so a key with spaces or `&` arrives whole), its answer passed on with its
307
+ `at` and `running`; no snapshot is fetched and the session file is not read. No reply, or one other than 200 or 404, is
308
+ `502 bridge_error`: the page marks its ask failed and asks again at the next event, instead of drawing lagging messages
309
+ it would not ask again for. An older worker without the feature, or one answering 404 (no such route), is read as
310
+ before: `working_set_source` over its snapshot's messages; with no live worker the file's (no Bridge call). Either way
311
+ the session's strategy and folder. `&latest=1` (the peek) answers `Timeline#peek_h` instead: only the events
312
+ `ws_timeline.js peekOf` picks (the latest edit with a diff and the newest event after it, else the newest run that isn't
313
+ an edit), the per-op `counts` (`read`, `edit`) and `latest: true`. Its texts
288
314
  are whole (about 1.7k lines at the most seen in real sessions): the tool limits bound them (`read.truncate_at_bytes`,
289
315
  the ToolRunner cap), so the page asks this route, never a row's `output` (a 2000-char `ToolOutputCut::WEB_PREVIEW_CHARS`
290
316
  preview for a long one). 400 without a known `kind` and a `key`.
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 first, in both modes: a skip ("the session is
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
data/docs/sessions.md CHANGED
@@ -41,11 +41,11 @@ A new session field is one `Session::FIELDS` row, plus a `SessionSetup` member w
41
41
 
42
42
  **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
43
 
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.
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 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
45
 
46
- **Deleting a session:** `chi sessions delete ID...`, `/exit --delete` in a terminal and the Web UI's delete all go through `SessionManager.delete_session`: it resolves a unique prefix, removes `<id>.json` and the whole `<id>/` dir, and returns what it removed. A session a one-turn `chi --non-interactive` run has (`owner.lock` kind `tui`) is always refused. One a worker runs is refused unless the caller asks to stop it: then it stops the worker as `chi sessions stop` does and deletes once `owner.lock` is free (`--force` on the CLI, 10 s; the web page always, 2 s; `/exit --delete` after the worker agreed to exit, 10 s). A worker that outlives the wait leaves the session in place. A session whose worker is being started (the `<id>/starting` marker) is refused or stopped the same way, and the files go while the delete holds `owner.lock`, so a worker can't take the session in the middle; a worker that still had it loaded doesn't write it back. 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`).
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. Automatic deletes (the retention sweep, the scratch cleanup, the discard, the rollback, a schedule's prune) leave tasks running as before.
47
47
 
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.
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. **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
49
 
50
50
  **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
51
 
@@ -551,12 +551,16 @@ leave) for the owner lock, and resumes the session; a worker that doesn't let
551
551
  go in time is reported as "didn't take the restart" and nothing is resumed. A
552
552
  worker that took the lock meanwhile (the old one handed over after all) is
553
553
  not touched. It refuses first if disk shows a running turn, pending
554
- question or approval, queued input, or a running background task started by
555
- the session; the message directs the user to `chi sessions stop ID`, then any prompt.
554
+ question or approval, queued input, or a background task started by the
555
+ session that may still run (`SessionManager::RunningTasks`, as a delete reads
556
+ it: a live one, one it can't verify, an unreadable record; a record left
557
+ marked running whose pid is gone doesn't hold it); the message directs the
558
+ user to `chi sessions stop ID`, then any prompt.
556
559
  Reminders, a running `/btw`, and other in-memory worker state cannot be
557
560
  checked and may be lost in this fallback. A stopped worker (SIGSTOP or
558
561
  Ctrl-Z: `ps` state `T`) answers neither the ask nor a TERM, so a restart
559
562
  refuses it at once, before asking, with its pid and `kill -CONT PID`. A
560
563
  session whose stop is marked (stopped, or its worker being stopped) is refused
561
564
  before any of this (`stop_marked`: no successor would come).
565
+ A session being deleted is refused the same way (`deleting`).
562
566
  The web restart route behaves the same way.