samagotchi 0.177.0 → 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 (88) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +44 -1
  3. data/docs/architecture.md +5 -4
  4. data/docs/cli.md +31 -6
  5. data/docs/guardrails.md +1 -1
  6. data/docs/internals/background-tasks.md +23 -2
  7. data/docs/internals/bridge.md +17 -6
  8. data/docs/internals/bundles.md +4 -3
  9. data/docs/internals/participants.md +8 -5
  10. data/docs/internals/remote-sessions.md +6 -1
  11. data/docs/internals/session-lifecycle.md +176 -0
  12. data/docs/internals/web-frontend.md +14 -6
  13. data/docs/internals/working-set.md +33 -6
  14. data/docs/plugins.md +1 -1
  15. data/docs/releasing.md +3 -2
  16. data/docs/scheduling.md +8 -1
  17. data/docs/sessions.md +15 -9
  18. data/docs/testing.md +4 -2
  19. data/lib/samagotchi/bridge/card_store.rb +2 -19
  20. data/lib/samagotchi/bridge.rb +38 -6
  21. data/lib/samagotchi/bundle_command/check.rb +1 -1
  22. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  23. data/lib/samagotchi/compat.rb +0 -7
  24. data/lib/samagotchi/engine/events.rb +43 -0
  25. data/lib/samagotchi/engine/session.rb +7 -0
  26. data/lib/samagotchi/engine.rb +9 -3
  27. data/lib/samagotchi/event_fanout.rb +56 -0
  28. data/lib/samagotchi/guardrails/approvals.rb +0 -4
  29. data/lib/samagotchi/memory_bundle/shipped_update.rb +1 -1
  30. data/lib/samagotchi/note_delivery.rb +9 -4
  31. data/lib/samagotchi/plugin/sessions.rb +2 -1
  32. data/lib/samagotchi/revise_anchor.rb +2 -0
  33. data/lib/samagotchi/schedules.rb +12 -5
  34. data/lib/samagotchi/session_access/contract.rb +4 -0
  35. data/lib/samagotchi/session_access/local.rb +16 -4
  36. data/lib/samagotchi/session_access/remote.rb +42 -9
  37. data/lib/samagotchi/session_archive_command.rb +38 -10
  38. data/lib/samagotchi/session_chain/delete.rb +98 -25
  39. data/lib/samagotchi/session_chain/delete_preview.rb +2 -2
  40. data/lib/samagotchi/session_delete_command.rb +33 -10
  41. data/lib/samagotchi/session_inbox.rb +29 -0
  42. data/lib/samagotchi/session_inbox_delivery.rb +13 -5
  43. data/lib/samagotchi/session_lifecycle/allowed.rb +69 -0
  44. data/lib/samagotchi/session_lifecycle/canonical.rb +49 -0
  45. data/lib/samagotchi/session_lifecycle/reading.rb +65 -0
  46. data/lib/samagotchi/session_lifecycle.rb +59 -0
  47. data/lib/samagotchi/session_manager/delivery.rb +29 -6
  48. data/lib/samagotchi/session_manager/lifecycle.rb +33 -39
  49. data/lib/samagotchi/session_manager/removal.rb +117 -25
  50. data/lib/samagotchi/session_manager/running_tasks.rb +334 -0
  51. data/lib/samagotchi/session_manager/spawn.rb +2 -2
  52. data/lib/samagotchi/sessions_command.rb +1 -1
  53. data/lib/samagotchi/system_prompt.rb +22 -2
  54. data/lib/samagotchi/task_files.rb +37 -4
  55. data/lib/samagotchi/terminal_ui/attached_loop/exit_commands.rb +7 -1
  56. data/lib/samagotchi/terminal_ui/attached_loop.rb +1 -1
  57. data/lib/samagotchi/terminal_ui/local_link.rb +11 -3
  58. data/lib/samagotchi/tool_names.rb +1 -1
  59. data/lib/samagotchi/tools/memory.rb +29 -0
  60. data/lib/samagotchi/tools/task_runtime.rb +25 -6
  61. data/lib/samagotchi/turn_anchors.rb +5 -0
  62. data/lib/samagotchi/verify_anchor.rb +2 -0
  63. data/lib/samagotchi/version.rb +1 -1
  64. data/lib/samagotchi/web/app.rb +5 -1
  65. data/lib/samagotchi/web/participant_show.rb +3 -4
  66. data/lib/samagotchi/web/participant_view.rb +4 -6
  67. data/lib/samagotchi/web/public/data.js +19 -3
  68. data/lib/samagotchi/web/public/delete_sheet.js +67 -11
  69. data/lib/samagotchi/web/public/running_tasks.js +73 -0
  70. data/lib/samagotchi/web/public/session_actions.js +57 -8
  71. data/lib/samagotchi/web/public/stop_sheet.js +3 -2
  72. data/lib/samagotchi/web/public/working_set.js +3 -28
  73. data/lib/samagotchi/web/public/working_set_view.js +5 -2
  74. data/lib/samagotchi/web/public/ws_item_sig.js +51 -0
  75. data/lib/samagotchi/web/public/ws_peek.js +23 -13
  76. data/lib/samagotchi/web/public/ws_reader.js +22 -12
  77. data/lib/samagotchi/web/public/ws_sections.js +1 -0
  78. data/lib/samagotchi/web/public/ws_timeline.js +9 -6
  79. data/lib/samagotchi/web/session_control.rb +66 -16
  80. data/lib/samagotchi/web/session_summary.rb +7 -0
  81. data/lib/samagotchi/web/working_set_routes.rb +29 -8
  82. data/lib/samagotchi/worker_boot.rb +9 -6
  83. data/lib/samagotchi/worker_link.rb +9 -1
  84. data/lib/samagotchi/worker_presence.rb +4 -0
  85. data/lib/samagotchi/working_set.rb +26 -0
  86. data/lib/samagotchi/working_set_command.rb +10 -7
  87. data/lib/samagotchi/working_set_steer.rb +3 -10
  88. metadata +9 -1
@@ -0,0 +1,176 @@
1
+ # Session lifecycle
2
+
3
+ There is no persisted lifecycle enum. A state is derived from the session file, sidecar files, locks, and the worker
4
+ link: `SessionLifecycle.read(id)` (`session_lifecycle.rb`) reads them once (`WorkerPresence` with its link looked at,
5
+ never unlinked, and `ContinueIntent.in_flight`) and names the first of its 15 states whose facts hold (Derived states).
6
+ The same session can satisfy more than one fact (archived while its worker is leaving); the precedence picks one. One
7
+ decider reads `SessionLifecycle`: `restart_session`'s precheck (Allowed operations). The others still read their own
8
+ subset of the facts in their own order, and what each answers per state is `ALLOWED` (Allowed operations), pinned by
9
+ the characterization matrix. The session file layout and user-facing session behavior are in [Sessions](../sessions.md); the Worker and
10
+ SessionManager boundaries are in [Architecture](../architecture.md) and [Engine internals](engine.md).
11
+
12
+ ## Facts and markers
13
+
14
+ | Fact | Writer and removal | Cross-process readers and how they see change |
15
+ |---|---|---|
16
+ | `<id>.json` `status` | `Session#save` writes the session snapshot; the owner is the normal writer. `Session#load` overlays `stopped` as `stopped` without rewriting the file. | `SessionRow` and `SessionAccess::Local` read saved turn status; stop cancellation, restart fallback, and archive refusal also use it as a busy hint. Readers reload the file; the hub refreshes rows on its tick. It is turn state, not proof of liveness. |
17
+ | `starting` (`{pid, at}`) | `SpawnPart#spawn_session` marks before the first session file; `#spawn_worker_for_session` marks around `Process.spawn`; `#claim_start` claims with `StartingMarker.claim`. Failures clear it; `Worker#start` clears it after acquiring `owner.lock`. A stale/dead marker is taken over after 60 seconds or when its pid is gone. | `WorkerPresence`, resume, archive, delete, and retention read it directly; `WorkerPresence` checks age and pid. The session hub also refreshes presence. The atomic hard-link claim arbitrates competing starters; there is no event notification. |
18
+ | `owner.lock` and `leaving_at` | `OwnerLock.acquire` creates the file, takes its exclusive flock, and writes `{pid, kind, started_at}`; `OwnerLock#mark_leaving` adds `leaving_at` and `leave_wait`; `#release` unlocks and closes but leaves the file. Deletion removes it with the session directory. | `OwnerLock.owner` probes the kernel flock, then reads the record. The kernel releases the lock on process death; the record alone does not establish ownership. Presence and `WorkerLink` decisions probe it; hub presence refreshes poll it. `leaving_at` marks a worker that closed its Bridge but still holds the lock for leave work. |
19
+ | `bridge.json` | `Bridge#write_sidecar` publishes the worker endpoint; `Bridge#remove_sidecar` removes its own sidecar when stopping. A crash can leave it behind. | `WorkerLink.resolve` combines the sidecar with `owner.lock` and pid; a sidecar alone is stale. Readers waiting for a worker poll `WorkerLink.resolve`; a stale unlink rechecks the owner and removes only the unchanged file. Live clients see worker events over Bridge SSE. |
20
+ | In-memory exit claim | `Worker#exit_request` uses `WorkerExitClaim#claim`, `#accept`, `#release` and `#forget`; `#stopped!` records the last stop-all. It dies with that Worker. | Only that worker's threads read it; the Bridge's `/exit` and the loop coordinate through the Engine event lock, not a cross-process file. |
21
+ | `stopped` | `SessionManager#stop_session` calls `Session.mark_stopped`; `SpawnPart#resume` and delivery's `#start_for_send` clear it with `Session.clear_stopped` when starting for a person. Session-directory deletion removes it. | `WorkerPresence`, the worker startup/signal paths, and `Session#load` check the marker. It is read from disk on a decision (and on the hub refresh); no worker event is required. Its timestamp is compared with `starting.at` so a stop cancels an older start, not a later resume. |
22
+ | `archived` | `ArchiveStore.archive` is called by `SessionManager#archive_session`; `ArchiveStore.unarchive` is called by `#unarchive_session`, `SessionContinue#undo_failed_continue`, and the chain-delete undo/revival paths. Session-directory deletion removes it. | Lists, chain resolution, delivery, schedules, retention, and `WorkerPresence` call `ArchiveStore.archived?` against the file; changes are seen by the next read or list refresh. |
23
+ | `continue.lock` and `continue.json` | `SessionContinue#with_lock` takes the exclusive lock for a continue; `ContinueIntent#hold` takes a nonblocking shared lock for readers that must exclude a continue. `ContinueIntent#write` records the successor before archive and updates the archived ids after; failed-continue cleanup removes the intent. The lock file remains until session-directory deletion. | Followed sends, schedules, chain deletion, and `ContinueIntent.in_flight` inspect the lock and intent. flock coordinates the live transition; readers reload the JSON. An intent without a held lock is a crashed continue, not an active one. |
24
+ | `parent.json` | `Session#reparent` writes the override when `ChildMove` moves a child. Session-directory deletion removes it. | `ChildReports` resolves the current parent when routing a ring; the worker reads the override when loading its parent. Readers reload the file; it is not an event stream. |
25
+ | `reminders.json` | `Worker::LeavePart#carry_reminders` writes it for an asked restart, or removes it when stopped/no successor; stop, archive, and a stopped restart also remove it. `ReminderCarry#take` reads and removes it at worker start. | Only the next worker restores it into its Engine. It is a one-shot hand-off, not polled state; the session id, 120-second window, and stop marker are checked before restore. |
26
+ | Pending `input/`, `children/`, and `notes/` | `SessionInbox.write_input`, `#write_ring`, and `#write_note` write the files. A worker claims input and notes by atomic rename to `.processing`, then removes or settles them; rings are consumed by `ChildReports`. Session-directory deletion removes all three. | The worker checks input around turns and on its idle loop; rings and notes are checked by worker wake/absorption paths. The file is the durable queue; Bridge SSE can announce a live turn, but the worker's file scan is the fallback and recovery path. |
27
+ | Turn checkpoint and pending question | `TurnCheckpoint` writes the running turn overlay at iteration boundaries and clears it at settlement/end; `QuestionDesk` updates `Session#pending_question`, persisted by `Session#save` and cleared on answer/settlement. | The next worker settles a checkpoint on startup instead of replaying the dead turn. Session readers and Bridge snapshots read the pending question; answers go through the live Bridge when present. These are session data, not liveness locks. |
28
+ | `scratch` | `SpawnPart#spawn_session` saves the flag in the session file. There is no separate marker; terminal/worker cleanup deletes the scratch session. | Inbox wake policy and worker boot read the session field. Scratch sessions are not resumed by ordinary delivery; their worker is removed when its terminal leaves. |
29
+
30
+ `SessionStores` registers cross-version sidecar ownership and removal with the session directory. The lists above focus on
31
+ the lifecycle facts; deletion takes the session's `owner.lock` as `deleting`, rechecks `starting`, then removes the JSON
32
+ and entire sidecar directory.
33
+
34
+ ## Derived states
35
+
36
+ `SessionLifecycle::STATES`, in precedence order (the first whose facts hold wins), as `Reading.derive` names them from a
37
+ `WorkerPresence` read with its link (`SessionLifecycle::Reading`: `state`, `presence` (also `facts`), `continuing`).
38
+ These are reader labels, not stored values:
39
+
40
+ | State | Facts that produce it |
41
+ |---|---|
42
+ | `absent` | No session file; a leftover sidecar directory may still exist (its facts are ignored). |
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`); restart refuses it (`deleting`); a schedule skips it ("the session is being deleted"). |
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`); a schedule skips it with Skew's short words. |
47
+ | `leaving` | The worker closed its Bridge and still holds the lock (`leaving_at`, `WorkerLink::Leaving`). |
48
+ | `booting_stuck` | A worker has held the lock past `WorkerLink::START_LIMIT` without its sidecar (`Starting`, stuck). |
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`). |
50
+ | `live` | A worker holds the lock and its sidecar matches it (`WorkerLink::Live`). |
51
+ | `stopped_starting` | No owner; the `stopped` marker and a fresh `starting` marker (archived or not). |
52
+ | `stopped` | No owner; the `stopped` marker (archived or not). |
53
+ | `archived_starting` | No owner, no stop; `archived` and a fresh `starting` marker. |
54
+ | `starting` | No owner, no stop, not archived; a fresh `starting` marker names a live starter. |
55
+ | `archived` | No owner, no stop, no start; `archived` has `archived_at`. |
56
+ | `idle` | The session exists with none of the above. |
57
+
58
+ The compound states exist because the deciders disagree on precedence: owner first (WakePolicy, resume, archive,
59
+ delete) or stop first (a schedule's busy check, a terminal's attach); WakePolicy reads archived before starting. Facts
60
+ that are not states: `continuing` (`continue.json` names a successor and `continue.lock` is held: only a send's and a
61
+ schedule's link resolution reads it), a stale sidecar (`WorkerLink::Stale`: a crashed worker's leftover, reads as
62
+ the no-owner state), and the other crashed leftovers (a checkpoint, a `.processing` file, an unlocked continue intent).
63
+ `SessionLifecycle::CANONICAL` holds the fewest facts per state, each deriving back to it; `stopping` is a worker whose
64
+ Bridge answers, with a stop, and `stopped_starting` a start marked before the stop.
65
+
66
+ A read costs what `WorkerPresence.read(link: :look)` costs plus a `continue.json` stat: idle about 8 probes and one
67
+ flock, no JSON (~20–50 µs); a live worker adds the owner record and `bridge.json` (~0.1–0.2 ms); a continue in flight a
68
+ lock probe and its JSON. The worst case is `OwnerLock.owner`'s blank-record retry (0.1 s).
69
+
70
+ ## Allowed operations
71
+
72
+ `SessionLifecycle::ALLOWED` (`session_lifecycle/allowed.rb`) is `{op => {state => cell}}`: every operation in every
73
+ state. A cell is `:go`, `:wait` or the decider's own refusal reason; `SessionLifecycle.verdict(op, cell)` reads it as
74
+ `:go`, `:wait` or `:refused` (resume's `live` and `starting` wait, restart's `fallback` goes).
75
+
76
+ - **Delivery columns** (send, note, push, ring, fresh_verdict, leave, schedule, plugin, delegate, participant,
77
+ automatic) are generated at load from `SessionInbox::WakePolicy::ROWS`, unchanged: each row's `decide` on
78
+ `CANONICAL[state]` (a worker asked for, no scratch file), `:start`/`:live` as go, `:starting`/`:stopped`/
79
+ `:archived`/`:none` as wait, `:gone`/`:owned`/`:deleting` as themselves. `:off` and `:scratch` are op-local.
80
+ `deleting` refuses every kind: `WakePolicy#refusal` before the write (nothing written), `#decide` after it (a
81
+ delete that took the lock between the two). What each kind does then: a turn delivery (`deliver_turn`, any sender)
82
+ answers 409 `DeliverResult::DELETING` ("the session is being deleted") and after its write takes its file back
83
+ (`SessionInbox.withdraw`; a file a worker claimed meanwhile stays delivered), also when the session went while it
84
+ wrote (and a folder the write made again goes); a note is a gone session's (`Session::NotFound`, its note taken
85
+ back); a ring, a push and a fresh verdict are refused before their write as for a gone parent (a push records to
86
+ its source's folder as for a gone session), and `wake_for_report` answers `:deleting`; a leave's respawn drops
87
+ (`why: deleting`).
88
+ - **Literal columns** (`LITERAL`): resume (`resume_session`), restart (`restart_session`: `stop_marked` in every
89
+ state with the stop marked: stopping, stopped, stopped_starting), stop (`stop_session`),
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", `deleting` the delivery's "the
92
+ session is being deleted", `worker_newer` `WorkerLink::Skew#short_message`) and attach
93
+ (`TerminalUI::LocalLink#live_worker`: `gone_stopped`, `gone_worker_newer`). They assume neutral op-local facts: not
94
+ scratch, saved status idle, no `input/`, no question or offer, not SIGSTOPped, features restart and activity, an idle
95
+ worker with no streams. Absent's delete and schedule cells are unreachable (a gone session is refused first).
96
+
97
+ Link resolution (`SessionInbox::Head.resolve`, `Schedules#target_of`) stays outside: the cells are the link's own.
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
+
103
+ `restart_session` is the first decider migrated to the table: its lifecycle precheck is `SessionLifecycle.read` (the
104
+ owner read through `session_owner`) and `ALLOWED[:restart]`: `owned_by_tui` raises `OwnedByTUI`, a refusal cell
105
+ raises `RestartRefused` with it as the reason (`starting`, `not_running`, `stop_marked`, `deleting`), `fallback` goes to
106
+ `restart_fallback` (skew, a stuck start) and `go` asks the live worker. Its op-local checks stay where they were: the
107
+ SIGSTOP check (`:stopped`, the worker's pid: a different condition with its own words, before the table's refusal),
108
+ the worker's `restart` feature, the Bridge's reply and the fallback's holds. The matrix still drives it, so its
109
+ column is pinned against the precheck and the op-local paths together. The other deciders don't read `ALLOWED` yet.
110
+
111
+ ## Characterization matrix
112
+
113
+ `spec/session_lifecycle/matrix_spec.rb` (rows, files and drivers in `spec/support/lifecycle_matrix.rb`) writes every
114
+ combination as real files: owner/link pairs (none, stale sidecar, tui, tui with a stale sidecar, deleting, a worker
115
+ Live, Starting, stuck, Leaving, Skew, an owner of unknown kind) × stop × starting × archived, one absent session, a
116
+ continue in flight on each archived no-owner row, and a start marked after the stop on each no-owner row with both
117
+ (the order is a row fact: `StartingMarker.claim` takes over only a start at or before `stopped_at`). The owner lock's
118
+ holder, `ContinueIntent.in_flight`, `Process.spawn`, TERM/CONT, the Bridge and the restart fallback are stubbed; no
119
+ process starts. Each row checks that `SessionLifecycle.read` names the state its facts derive, then drives every
120
+ operation (one driver each, every private reach in that one file) and projects its answer into a cell. A row the
121
+ code can't make (a one-turn run's lock with a stop) is marked `reachable: false` with its note and still asserted.
122
+
123
+ Every answer must equal `ALLOWED[op][state]` (for the session hub, `SHOWN[state]`: `Web::SessionSummary.build`'s
124
+ status and bridge_up, its `SessionRow`'s live), or be named by exactly one `KNOWN_DIFFERENCES` entry (op, a `when`
125
+ over the row, a plain reason); an entry that names no mismatch fails as stale. The entries are the findings for the
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;
129
+ `wake_for_report` reporting a worker's `:live` as `:owned`; the hub's bridge_up, live and status overlay. (Restart
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
133
+ generated from `WakePolicy::ROWS`, so for deliveries the matrix proves the states are drawn right (decide is a function
134
+ of the state), not what WakePolicy does; the literal columns and `SHOWN` are goldens.
135
+
136
+ ## Locks and crash repair
137
+
138
+ `owner.lock` is the single-owner boundary for an Engine; its flock is released by process death. A starting claim uses
139
+ an atomic link rather than a long-held lock. A continue holds its exclusive `continue.lock` across the transition;
140
+ shared holds protect followed sends and chain operations. When chain deletion nests locks, it takes the continue hold
141
+ before the `owner.lock` deletion locks. Inside a worker, the lock order is Engine event lock, then
142
+ `WorkerExitClaim`'s mutex. Session saves serialize through their per-session save lock. These locks protect separate
143
+ facts; there is no global lifecycle lock or atomic snapshot across all markers.
144
+
145
+ A worker that crashes exits 1 and is not respawned just because input is queued. A later delivery may start a new
146
+ worker; under its owner lock, startup settles a turn checkpoint and stale running status rather than replaying the
147
+ dead turn. Interrupted continue intents are repaired separately by session listing/the web hub or before another
148
+ continue (`SessionContinue.repair_interrupted`), not by worker startup.
149
+
150
+ ## Open windows
151
+
152
+ These are documented race boundaries, not promises of an atomic lifecycle transition:
153
+
154
+ | Window | Code comment / current behavior | Pin |
155
+ |---|---|---|
156
+ | A ring wake decides to start, then a stop lands before resume. | `SpawnPart#wake_for_report` (`session_manager/spawn.rb`): `resume_session` can clear that stop and start; the check and resume are not one transaction. | Unit spec: stop in the start callback and assert the worker is started and the marker cleared. |
157
+ | Empty-session discard races a delivery (closed for turns and notes). | `WorkerBoot#discard_left_session` (`worker_boot.rb`) checks emptiness after releasing the worker lock and again under the deletion lock (`delete_session`'s `still:`): a send or note that went in before the lock keeps the session. One that reads the session during the lock is refused (`DeliverResult::DELETING`, a note as gone); one that read it before the lock and wrote after it reads it again after its write and takes its file back (`SessionInbox.withdraw`), so no turn or note is reported delivered and then removed. No new lock: the write-then-reread and the recheck under the existing deletion lock close it. What remains: a ring or fresh verdict that read the session before the lock and wrote after it is not taken back: it goes with the directory, or stays for the next worker if the delete gives up; neither is reported to a person. | `run_session_loop_spec.rb`: a send at deletion-lock acquisition is refused; one just before the lock keeps the session. `delivery_spec.rb` / `note_delivery_spec.rb`: the lock (or the removal) between the check and the write, deterministic through the bridge / writer seam. |
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. |
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. |
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). |
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. |
164
+
165
+ ## Adding a transition
166
+
167
+ 1. Name the fact being changed and its on-disk format; add cross-version handling to `SessionStores` when applicable.
168
+ 2. Put the write/removal in its owning module and add the call site, with its reason, to
169
+ `spec/session_lifecycle_writers_spec.rb`.
170
+ 3. Identify every decider that reads the fact and how it observes the change (lock probe, direct read, poll, or SSE).
171
+ 4. If the change touches an open window above, extend its pin in the corresponding unit spec; don't hide a race with a
172
+ sleep or a process-wide integration test.
173
+ 5. If the fact changes a state, update `SessionLifecycle::STATES`/`Reading.derive` and `CANONICAL`, then the
174
+ `ALLOWED` cells (the literal ones by hand; the delivery ones follow `WakePolicy::ROWS`) and the matrix's rows; a
175
+ decider that answers otherwise is a `KNOWN_DIFFERENCES` entry with its reason, never a silent cell change.
176
+ 6. Recheck lock order, crash cleanup, and the existing file-format/compatibility specs before changing runtime behavior.
@@ -20,7 +20,9 @@ Verify, the composer's mode and the strip's hide went into modules of their own.
20
20
  its own, wired from `app.js` in a few lines; a refactor that shrinks `app.js` ratchets its cap down with it. Never
21
21
  raise either: extract instead. Ruby's twin is `Samagotchi/FileSize` (docs/testing.md, File size).
22
22
 
23
- **New exports go in new modules.** The static JS is served at unversioned URLs. Today every load revalidates
23
+ **New exports go in new modules.** An `npm test` ratchet parses every public module and compares existing modules'
24
+ exports with `spec/web/public/exports_baseline.json`; `release:bump` refreshes the baseline. Its `ALLOWED` entries
25
+ name the file and export and carry a one-line reason. The static JS is served at unversioned URLs. Today every load revalidates
24
26
  (app.rb `serve_static` sends `Cache-Control: no-cache` with a content ETag, and `sw.js` has no fetch handler), but an
25
27
  open tab still holds the modules it loaded, and a proxy that ignores `no-cache` can serve an old one: a new export
26
28
  on an existing module, imported by a new version of another, then finds the old module without it and blanks the
@@ -29,7 +31,7 @@ page. A factory dep a new version stops passing is the same hazard the other way
29
31
  out of `send_turn.js`, `session_actions.js` and `lists_view.js`); a page loaded before keeps all its old modules
30
32
  until a reload, so the risk is a mixed cache, not an open tab. `answer_fold.js`, `details_motion.js`,
31
33
  `turn_range.js`, `history_reveal.js`, `latest.js`, `session_payload.js`, `method_api.js`, `session_store.js`,
32
- `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).
33
35
 
34
36
  ## One page, every viewer
35
37
 
@@ -390,8 +392,10 @@ is no longer the live one (a ✕ on another card while the first plan was read)
390
392
  `GET /api/sessions/:id/delete_plan`, fetched as it opens and only for a chained session: the server's own plan and
391
393
  refusals (`SessionChain::Delete::Preview`, the code the delete runs), so the sheet and the delete can't disagree; its
392
394
  cost is one session listing walk per open. `deleteChoices` (pure) turns it into the two choices, a schedule's banner
393
- and each refusal's "Not while …"; a plan that says no chain (a link alone past a gap) falls back to the confirm. A
394
- stale plan is fine: the delete refuses as it does, and `runDeleteFlow` shows the refusal in the sheet
395
+ and each refusal's "Not while …"; a plan that says no chain (a link alone past a gap) falls back to the confirm. The
396
+ confirm sends the shown choice's `digest` (`expect=`, `data.js deleteSession`/`deleteChain` keep it out of `fetch`);
397
+ a `409 plan_changed` re-reads the plan and redraws the sheet with "What this deletes changed; check again" (a link no
398
+ longer chained gets the plain confirm). Any other refusal `runDeleteFlow` shows in the sheet
395
399
  (`refusalModel`: a moved delegate that can't go back offers "Stop its worker, then delete" only when the 409 says
396
400
  `stoppable`; it stops each, retries only once the stop answers `released`, and says so otherwise, never looping, one
397
401
  stop at a time).
@@ -644,8 +648,12 @@ for the set, its jumps and its list, and `whatChiHas` for refs.js), `ws_way_in.j
644
648
  flag turn_html.js reads; on only once the reader is attached). State: the reader's own closure (the open item, its
645
649
  answer, the tab), never `store.current`. The reader is a `section` in `#center` over the history and the composer
646
650
  (both `inert` while it is open, so their scroll place stays; a phone's is `position: fixed`). Each item answer goes
647
- through `createLatest` keyed by the session and the item; a new server snapshot (`onServer`) asks again while it is
648
- 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
649
657
  forgetSession` (a switch, the start page, + New, a deleted or archived session) calls `wsPreview.reset()`, so
650
658
  `#center` is never left inert, whatever the next session's GET does; close gives focus back to where it was at the
651
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
 
@@ -227,7 +245,8 @@ projection), on both loops. It costs one model step; a model may skip it (the no
227
245
  those), what the caller's `found` look says can't be read (`WorkingSetCommand#missing`: a file not there or a
228
246
  directory; a memory name `memory_read` rejects or that neither scope holds), an item holding the user's drop
229
247
  (`undrop_first`: undrop brings it back without a step), one already in the system prompt and with no working-set
230
- output (`in_prompt`: nothing to add), and one the model has whole (`already_sent`: live, a read of it sent). The
248
+ output (`in_prompt`: nothing to add; matched by name and scope, `Tools::MemoryRead.prompt_memory?` over
249
+ `Engine#prompt_memories`, a bare name or an unscoped prompt entry by name only), and one the model has whole (`already_sent`: live, a read of it sent). The
231
250
  prompt-only refusal doesn't apply when the set holds a read of that memory: a stale or forgotten item may still be
232
251
  added as the web row's `refresh`. **`unadd`** takes a pending add back (free); without one it is refused
233
252
  (`not_added`).
@@ -282,8 +301,16 @@ file is; nil without a stamp.
282
301
 
283
302
  **The route.** `GET /api/sessions/:id/working_set/item?kind=&key=` (`WorkingSetRoutes#handle_working_set_item`,
284
303
  `:owner, :session`: a participant gets 403 from `not_permitted_for`) answers `timeline.to_h`, and with `&now=1` for a
285
- memory `now:` too. Unlike the set's route it never answers a worker's precomputed set: it builds from
286
- `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
287
314
  are whole (about 1.7k lines at the most seen in real sessions): the tool limits bound them (`read.truncate_at_bytes`,
288
315
  the ToolRunner cap), so the page asks this route, never a row's `output` (a 2000-char `ToolOutputCut::WEB_PREVIEW_CHARS`
289
316
  preview for a long one). 400 without a known `kind` and a `key`.
data/docs/plugins.md CHANGED
@@ -1248,7 +1248,7 @@ ctx.sessions.stop(id) # one of this session's own children
1248
1248
  - `send(id, text)` sends a user message to a session (an id or a unique
1249
1249
  prefix); it runs as a turn, and an idle session is woken. A session its
1250
1250
  owner stopped or archived is not: `Error` (`session_stopped` /
1251
- `session_archived`), nothing sent. It waits up to
1251
+ `session_archived`), nothing sent; nor one being deleted (`session_deleting`). It waits up to
1252
1252
  5 s for the session's worker, so call it from an anytime command or a
1253
1253
  thread of your own, never from a tool or hook of a running turn. A
1254
1254
  session a `--non-interactive` one-shot has can't take it.
data/docs/releasing.md CHANGED
@@ -76,7 +76,7 @@ as the GitHub release body.
76
76
  | `rake lint` / `rake lint:fix` | RuboCop over the repo (must report no offenses; CI runs it) / its safe autocorrect (`rubocop -a`). |
77
77
  | `rake gem:validate`, `gem:build`, `gem:install`, `gem:clean` | Check the gemspec; build the gem into `pkg/`; build and install it locally; remove the built gems. |
78
78
  | `rake release:draft_changelog` | A draft Unreleased section from the commit subjects since the last tag, grouped. Stdout only. |
79
- | `rake release:bump[X.Y.Z]` | VERSION, the system manifest, Gemfile.lock, CHANGELOG, a compatibility corpus at `spec/compat/X.Y.Z/` written through the current state writers (with `wire/`: a real Engine and Bridge's replies, recorded twice and refused if the two differ), refreshed `spec/shared/compat_wire/*.json` fixtures, and `requires_chi: ">= X.Y.Z"` for each bundle marked `requires_chi_next` (the marker dropped), then a profile left below a member's `requires_chi` raised to it, with a patch bump of its version (none when it moved since the last tag) and named in the CHANGELOG's "Update with `chi update`" line, and each entry an `# Unreleased` comment in `Plugin::Api::SINCE` or `Manifest::SINCE` names moved into the table at X.Y.Z (the comment dropped). No commit; commit the corpus and fixtures with the release. |
79
+ | `rake release:bump[X.Y.Z]` | VERSION, the system manifest, Gemfile.lock, CHANGELOG, a compatibility corpus at `spec/compat/X.Y.Z/` written through the current state writers (with `wire/`: a real Engine and Bridge's replies, recorded twice and refused if the two differ), refreshed `spec/shared/compat_wire/*.json` fixtures, `spec/web/public/exports_baseline.json` rebuilt from the public modules, and `requires_chi: ">= X.Y.Z"` for each bundle marked `requires_chi_next` (the marker dropped), then a profile left below a member's `requires_chi` raised to it, with a patch bump of its version (none when it moved since the last tag) and named in the CHANGELOG's "Update with `chi update`" line, and each entry an `# Unreleased` comment in `Plugin::Api::SINCE` or `Manifest::SINCE` names moved into the table at X.Y.Z (the comment dropped). No commit; commit the corpus, fixtures and baseline with the release. |
80
80
  | `rake release:check` | Clean tracked tree, VERSION == system bundle, a CHANGELOG section, no `requires_chi_next` left, no `# Unreleased` comment left in `Plugin::Api::SINCE` or `Manifest::SINCE`, `bundles:check`, `rake lint` (RuboCop) + `npm run lint` (the web frontend's ESLint), rspec (both roots: `spec` and the bundles' own `spec/`) + `rake bundles:specs` + npm test, `gem build`, then a clean install into a temp GEM_HOME that runs `chi --version`, `chi self` and `chi bundle list` with a temp HOME. Needs the network (gem dependencies). |
81
81
  | `rake release:notes[X.Y.Z]` | Prints the CHANGELOG section (default: the current VERSION). |
82
82
 
@@ -119,7 +119,8 @@ The agent does each step and stops where the user has to say yes.
119
119
  `spec/compat_spec.rb` names it, and the shim goes (or its date moves)
120
120
  before the release. The bump also refreshes `spec/shared/compat_wire/*.json`
121
121
  by running `UPDATE_COMPAT_WIRE=1 bundle exec rspec spec/compat/wire_readers_spec.rb`;
122
- commit those fixtures with the release corpus. If that refresh fails, the
122
+ rebuilds `spec/web/public/exports_baseline.json` from every public module
123
+ except `vendor/`; commit both with the release. If either refresh fails, the
123
124
  bump is already written; follow its rerun command before reviewing or committing.
124
125
  5. **Check.** Add all release files, including the new compatibility corpus, then run it:
125
126
  `git add -A && git commit -m "Release X.Y.Z"` and `bundle exec rake release:check`.
data/docs/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
@@ -25,13 +25,13 @@ A session is deleted if **expired by age OR overflow by count** (unless `keep_st
25
25
 
26
26
  **Worker idle exit:** a background worker (plain `chi`, Web UI sessions) exits after `SAMAGOTCHI_SESSION_IDLE_EXIT_MINUTES` (`session.idle_exit_minutes`, default `30`, `0`=never) with no turn running or queued, no client on its stream (an open web tab or attached terminal keeps it), no reminder registered, no background task it watches for a [finish wake](internals/background-tasks.md#finish-wake) still running or waiting for its wake turn (with `session.task_wakes: wake`; not one whose turn you stopped) and no continue offer (the step-limit question) waiting for an answer. It removes `bridge.json` and frees `owner.lock`; the next prompt or `--attach` wakes a new worker (`WorkerIdleExit`, `WorkerBoot.run_session_loop`). As its Bridge stops, the worker marks the lock leaving (`OwnerLock#mark_leaving`: `leaving_at`, and `leave_wait`, its `recap.timeout`), since it keeps the lock while it writes the recap on leave: an `--attach` or `--resume` meanwhile (here, or a remote one through chi web's wake) prints `(waiting for the session to finish its recap…)` (`LaunchMode::RECAP_WAIT`) and waits for the release, up to that budget plus `OwnerLock::LEAVE_MARGIN` (5 s), before starting the new worker (`OwnerLock.await_release`). A lock held by a worker that isn't leaving (a live one, a stuck one) is left as before. A client can also ask the worker to exit right away (Bridge `POST /session/:id/exit`; `/exit` in an attached terminal does, `/detach` doesn't): the same rules apply without the timeout (even with `0`), and the asker's own stream doesn't count. The reply names what keeps it up (for background tasks, which ones and how to stop them). When every hold is one the user can stop — reminders, a watched task still running, a delegate with a live worker — the 409 also carries `holds: [{kind:, items: [{id:, label:, detail:}]}]` (a reminder's detail is its schedule, `every 20m`/`every 1h`, `, due now` when it is already due), and an attached terminal asks what to do with them; its "stop them and exit" posts `{"stop": "all"}`, which clears the reminders, stops those tasks (`TaskRuntime.stop_task`, as `task_stop`) and stops those children (`SessionManager.stop_session`) before leaving, re-checking first that nothing the user can't stop appeared meanwhile (`HoldStop`). A delegate counts only for that ask: it never holds the idle exit, and an exit that deletes or archives the session does not ask about it. The session's status stays as it was, not `stopped`. With `"restart": true` (a worker whose sidecar lists the `restart` feature) the worker hands the session to a new worker on the newest chi installed: it leaves, then starts its successor once its lock is free, keeping even an empty session and writing no recap. Clients' streams don't hold a restart (a web tab and an attached terminal reconnect to the new worker); what would be lost does: a turn running or queued, a continue offer, a question or approval waiting, a `/btw` (or another anytime command) still running, a delegate's approval relay open or settled in the last 10 minutes, and background tasks this conversation started that still run (`WorkerIdleExit#hold_for_restart`; 409 `held` with `reason`). Reminders go along: as it leaves, the worker writes them to `<id>/reminders.json` (0600: `session_id`, `written_at`, and each reminder's id, name, description, interval and next fire as wall-clock time; `ReminderCarry`), and its successor reads and deletes the file as it starts, before its idle scheduler runs. A restored reminder keeps its id and schedule; one that came due meanwhile fires once at once, and one further ahead than its interval (a clock that jumped) is due one interval from now. The file counts only for the same session within 2 minutes of `written_at`, and not once the session is stopped: otherwise it is deleted unread (log `reminders_carry_dropped`, at warn unless the session was stopped). A stop that lands while the worker leaves for a restart wins: the worker writes no file, and no successor starts (`WorkerBoot.run_session_loop`, log `restart_dropped`). So does one that lands as it leaves any other way (an idle exit, `/exit`, a signal) with input queued or delegate reports waiting: no new worker un-stops it (log `respawn_dropped`), and what waits stays for the next start. A person's send after the stop (chi send, a web tab, a terminal) still un-stops it, as a person's send always does (see *Who may wake a session* below): one that reaches a leaving worker clears the stop, so the leave's new worker runs it (log `send_unstopped_leaving`); an archive deletes the file of each session it archives. Once an exit or restart is taken (claimed before a stop-all stops anything), the first one decides how the worker leaves: a later request of the same kind is answered as that exit, one of another kind (a stop-all from another terminal after a restart, chi web's "Restart workers" after a `/exit`) gets 409 `held` with `reason` `leaving_exit`, `leaving_delete` or `leaving_restart`, and a restart says it was refused rather than "restarted". A write that fails keeps the worker up with its reminders (log `reminders_carry_failed`), and the caller reports no new worker. A reminder already due when the restart is asked runs its turn first, so the restart's wait (10 s) may report no new worker yet though the hand-off follows. A worker from before this still refuses a restart for its reminders (409 `reminders`). Only an asked restart carries them: the fallback's TERM (a worker that can't be asked, below), a stop, an idle exit (which reminders hold anyway) and a crash drop them as before. What lives only in the worker's memory goes: the event history a late client replays, the kept `/btw` answers, a plugin's in-memory state.
27
27
 
28
- **Empty sessions:** a session nothing happened in is deleted when it is left, so `chi` → `/exit` leaves no trace. Empty means: no messages, no turn tried (a failed turn leaves a `last_prompt` and keeps it), no memory used, no pending question, nothing in `input/`, `notes/` or `images/`, nothing in its dir beyond the worker's skeleton, mode `assist`, and the default model. A session on another model (`/model`, `--model`) counts as prepared and stays (`SessionManager.discardable?`). The worker checks as it idle-exits or leaves on a client's request and deletes it once its lock is free, checking again first. The attached `/exit` then says `Detached; the session is empty: it will be discarded if nothing arrives before its worker stops.` (a note or prompt landing first keeps it). The retention sweep catches those killed first: empty sessions over an hour old with no live owner, whatever `DAYS`/`MAX`, and skeleton-only dirs with no `*.json` (removed as a delete removes, every session store, under the session's lock: a worker or a start that took the session since the check keeps it, and so does one whose file or content was written meanwhile, read again under that lock). `session.keep_empty: true` (env `SAMAGOTCHI_SESSION_KEEP_EMPTY`) turns all of it off.
28
+ **Empty sessions:** a session nothing happened in is deleted when it is left, so `chi` → `/exit` leaves no trace. Empty means: no messages, no turn tried (a failed turn leaves a `last_prompt` and keeps it), no memory used, no pending question, nothing in `input/`, `notes/` or `images/`, nothing in its dir beyond the worker's skeleton, mode `assist`, and the default model. A session on another model (`/model`, `--model`) counts as prepared and stays (`SessionManager.discardable?`). The worker checks as it idle-exits or leaves on a client's request and deletes it once its lock is free, checking again first and once more under the delete's lock (a prompt or note that went in before that keeps it). The attached `/exit` then says `Detached; the session is empty: it will be discarded if nothing arrives before its worker stops.` (a note or prompt landing first keeps it). The retention sweep catches those killed first: empty sessions over an hour old with no live owner, whatever `DAYS`/`MAX`, and skeleton-only dirs with no `*.json` (removed as a delete removes, every session store, under the session's lock: a worker or a start that took the session since the check keeps it, and so does one whose file or content was written meanwhile, read again under that lock). `session.keep_empty: true` (env `SAMAGOTCHI_SESSION_KEEP_EMPTY`) turns all of it off.
29
29
 
30
30
  **Participants:** a session its owner invited participants into (`chi share`, see [CLI: Participants](cli.md#participants)) has two more files in its dir, neither in the session JSON: `participants.json` (0600), who is or was invited (`{participants: [{id, kind, name, role, added_at, expires_at, removed_at}]}`, never a token), which chi web and `chi share` write and the worker reads (`Participants.read`); and `participants.jsonl` (0600, append-only), the audit trail (grants issued, revoked and expired, each new peer, refused routes). A session nobody was invited to has neither. A continue, a fork or a delegate starts with no participants. Archiving or deleting the session revokes its links. See [internals/participants.md](internals/participants.md).
31
31
 
32
32
  **Always attached:** every interactive `chi` (plain, `-p`, `--resume ID`, `--attach ID`, `chi scratch`) runs its session in a background worker and attaches to it; there is no setting for it. The worker runs in the session's `working_directory`, so `!commands` and tools see the directory the session was started in. Only `chi -p TEXT --non-interactive` runs its one turn in this process; while it does, the session can't be attached ("in use by a one-turn chi --non-interactive run or an older chi's terminal"). See [CLI: Sharing a session](cli.md#sharing-a-session).
33
33
 
34
- **Who may wake a session:** every turn delivery names its sender (`SessionManager.deliver_turn` requires `client_id`), and the sender's kind picks what it may do to the worker (`ClientId.wake_kind`, `SessionInbox::WakePolicy.for_sender`). A person — `chi send`, a web tab, an attached terminal — starts an idle session, un-stops a stopped one and brings back an archived link. A schedule's firing, a plugin's `ctx.sessions.send`, a `delegate` follow-up, a participant's turn and any sender chi doesn't name start an idle session only: a session its owner stopped or archived refuses them (409 `session_stopped`, "the session is stopped; only its owner's message starts it again", or `session_archived`, "…brings it back"), nothing written. A schedule counts that as a skip (and skips a stopped session at its check, [scheduling.md](scheduling.md)); `delegate` says it as `Error: session <id8> refused: …`; a plugin gets `Error`. A turn already handed to a live worker is that worker's, as before. chi web's owner turn and command routes name a body that carries no `client_id` as `web:unnamed` (a web tab's rights).
34
+ **Who may wake a session:** every turn delivery names its sender (`SessionManager.deliver_turn` requires `client_id`), and the sender's kind picks what it may do to the worker (`ClientId.wake_kind`, `SessionInbox::WakePolicy.for_sender`). A person — `chi send`, a web tab, an attached terminal — starts an idle session, un-stops a stopped one and brings back an archived link. Nobody's message goes into a session being deleted (409 `session_deleting`, *Deleting a session* above). A schedule's firing, a plugin's `ctx.sessions.send`, a `delegate` follow-up, a participant's turn and any sender chi doesn't name start an idle session only: a session its owner stopped or archived refuses them (409 `session_stopped`, "the session is stopped; only its owner's message starts it again", or `session_archived`, "…brings it back"), nothing written. A schedule counts that as a skip (and skips a stopped session at its check, [scheduling.md](scheduling.md)); `delegate` says it as `Error: session <id8> refused: …`; a plugin gets `Error`. A turn already handed to a live worker is that worker's, as before. chi web's owner turn and command routes name a body that carries no `client_id` as `web:unnamed` (a web tab's rights).
35
35
 
36
36
  **Which chi a worker runs:** a new or woken worker runs the newest chi installed for this Ruby (`gem 'samagotchi', '>= 0.a'`, prereleases count), whoever starts it: a `chi web` or terminal still on an older chi starts it on the newest one, so a stale process doesn't spread old code. A worker already running keeps its version until it is restarted. Should the newest install fail to load, the worker runs the starter's own version and logs `boot_fallback` (its stdio is `/dev/null`). Under `bundle exec` the worker drops Bundler's env first, so it activates the newest gem too. Two consequences: a wrapper pin (`chi _0.17.0_ web`) pins only that process, not the workers it starts; and a source checkout (`bin/chi` in a worktree, `bundle exec`) starts its workers on its own `lib/`, but a session it made that is later woken by an installed chi (`chi web`, `chi send`) runs the installed code. The names an older starter hands a newer worker (the boot line, its env keys, `input/` files, the session JSON fields and the Bridge routes sessions use on each other) are pinned in `spec/worker_contract_spec.rb`. A chi newer than 0.130.0 keeps the top-level keys it doesn't know (a newer chi's fields) when it saves a session, after its own, and doesn't act on them; `written_by` names the chi that saved the file last, and a worker woken on a file a newer chi saved logs `newer_writer`. chi 0.130.0 and older drop those keys: a session a newer chi made loses its newer fields when an older chi wakes or saves it (for example `chi --attach` from a project whose Ruby has an older chi). Keep the chi in every Ruby you run it from newer than 0.130.0.
37
37
 
@@ -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. 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
 
@@ -386,7 +386,7 @@ A session can **continue** an earlier one: "the next run of the same routine" (a
386
386
  - **The page:** the info bar's `continue →` continues the open session (`continues: <id>, idle: true`; it reads `continuing…` through the recap wait) and opens the new link with an opener in the composer, not sent (a draft written in this session stays instead; one carried over from another session or the start page gives way to the opener, and the toast's **Restore draft** brings it back): the previous link's own first typed message when that link continues one (the 201's `opener`; a `!shell` line isn't taken), else `Continue where we left off.`. So whatever you sent on the last link comes back on the next one, and editing it once changes it for every later link; the previous link is archived, a toast says so (`Continued 3fa2c1d0 in 4b7e9a01; 3fa2c1d0 is archived; 1 open delegate moved`), and a moved delegate's card folds under the new link. When the previous link's model's host is gone the link starts on the default model and the toast carries the server's `model_warning` too, and then stays until closed. A fresh link (one with no turn yet, however it was made: `continue →`, `chi send --new --continues`, a reload) shows the model picker in its composer with the link's model, until its first turn starts (a failed or canceled first turn ends it too); a pick runs `/model <name>` in the link (a command bubble; the info bar follows) and changes neither the start page's remembered model nor its Recent list, and a Send right after it waits for the `/model` to be taken. A link a one-turn `chi --non-interactive` run has, or one continued already, shows none. A link continued already has no `continue →`: its `→` link goes to the next link (a stale page's continue answered 409 `continued` opens `next_id`). A continue refused for open delegates that can't move shows a toast that names each one (its preview and what the server says to do: `older chi worker 0.46.1; restart it`, `in use by a one-turn chi --non-interactive run or an older chi's terminal; let it finish`), each a link to its page; any other refusal shows the server's words. The info bar of a link carries `← 2026-10-08` (the previous link's day) and, on an earlier link, `2026-10-10 →`, each a link with its id, its full start (`2026-10-10 14:32`) and its preview in the tooltip; a neighbour that started on the open link's own day shows its time instead (`← 09:12`, `14:32 →`). A link made by `continue →` inherits the previous link's preview (and its title, if it has one) when it is created, so its card keeps its chain's title whatever opener it is sent, and its top bar and browser tab show its card's title. A link with a recap of its own reads its auto title, else its recap's first sentence, instead (a link without one reads its chain's name, and a first link's recap names its chain). A link whose title is the opener and nothing else (a `chi send --new --continues` link whose first message is `Continue where we left off.`) shows its chain's first link's title instead, on its card, in the popover and in its info bar's title line, display only (its messages and data keep the opener; its own title when the first link is gone). The lists fold a chain into the card of its latest listed link, whatever the earlier links' archived state (typing in an archived link brings it back, folded there still), their delegates with them: the card's `↩ #N` chip (`#N of M` when later links aren't listed; its tooltip `Session chain: link N of M`) opens a popover of the other links, newest first (`#N`, its date, with its time (`2026-10-17 14:32`) when another link of the chain started the same day, its own title when it differs from the card's (a link inherits its chain's, so mostly it doesn't), else its recap's first sentence, else its preview, `archived`), a click opens one; the chip shows a live dot or `waiting` for a link that has a worker or waits on the user, and a waiting link puts its chain's card first. All sessions folds nothing while a search is typed or the `archived` toggle is on: every link is a card of its own then, its chip `#N of M`, with its own delegates folded in, so a search finds an earlier link and its delegates.
387
387
  - **CLI:** `chi send --new --continues (ID|PREFIX|last:ID) [--model M] [-m TEXT]` (see *Starting a session*).
388
388
  - **Which link:** an id, a unique prefix, or `last:<id or prefix>`, the latest link of the chain that session is in. It walks the links that still exist: a deleted link in the middle (`chi sessions delete`, the retention sweep of an unarchived one) ends the walk before it, so `last:` of an earlier link then names that earlier link, and continuing it starts a second line beside the links after the gap; name a link after the gap instead. A trigger names the chain this way: a person's message to an archived link that nobody continued brings it back (a human's input), it doesn't continue the chain; an unattended sender's is refused (*Who may wake a session*). That is the rule: `chi send` and a note go to the chain's newest link (*Sending a message*, *Context notes*); the web composer, a participant's turn and `delegate(session:)` go to the link they name. One walker answers every one of these (`SessionChain::Links`: one session listing, archive flags read once; the earliest created successor wins a fork a hand edit made, a loop ends where it would repeat), with two rules on it, not unified on purpose: `last:` and a schedule take the chain's **end** (`Links#latest`: a continue refuses a link continued already, and a schedule never un-archives a chain you retired), `chi send` and a note the **first link not archived** (`Links#first_live`: a person's input goes where the chain is live, and brings back an archived end). A chain pruned by a schedule keeps its `anchor`: the kept window's oldest link still names a link that is gone, so the walk simply stops there; the page's chip counts from the surviving root (pruning renumbers the links) and its popover says `earlier links pruned` where the walk stops, rather than linking to a deleted session.
389
- - **Deleting a link** (`SessionChain::Delete`; the CLI, the web and `/exit --delete`): a link of a chain is deleted alone by default, and what follows depends on where it is. **The newest link** (nobody continues it, it isn't archived itself, the link before it is archived) undoes its continue: the delegates the continue moved go back to the previous link, finished ones too (`continued_from.json`'s `moved_ids`, still under the link; without the record, its children whose `parent.json` says they came from the previous link), each with a note saying the link was deleted; every note waiting in the link but the continue's own goes back too (`NoteMove.give_back`); then the previous link and what the continue archived with it come back to the lists (without the record, the previous link alone). The previous link is **not started**: reports a moved-back delegate left wait for its next start. What dies with the link: its turns, context sources, objectives edits, session approvals and participant grants (the previous link kept its own copies). Every refusal comes before anything goes: the link's delegates that would go are checked too (a schedule on one, a one-turn run), and they and the link are removed (and the undo runs) only under their `owner.lock`s (kind deleting, taken without waiting, so a worker that took one refuses it); a moved delegate that can't go back (`ChildMove.unmovable`: an older chi's worker, a one-turn run) refuses it (`delegate_unmovable`, naming it), as does a worker that took the link after the stop. Deleting the links one after another undoes each continue by its own record. **A middle link** splits the chain (the earlier links stay archived, the later ones go on as their own chain); nothing is undone or re-linked. A link whose chain is all archived stays archived around the gap. **The link's own delegates** (any position) follow one rule, `SessionChain::Delete::DELEGATES`: a running one (a worker owns it or is starting for it, a one-turn run; a saved `running` with no worker is a crashed run, and goes) is left running with its whole subtree, its file untouched (its parent's id names a deleted session; its reports are refused as for any gone parent); every other node under the link goes, deepest first, before the link. A session in no chain (a link alone past a gap too) is deleted as before. **The web asks first**: for a chained session, chi web's delete sheet reads `GET /api/sessions/:id/delete_plan` (`:owner`; no query or body; no-store), `SessionChain::Delete::Preview` over the same `LinkPlan`/`ChainPlan` and checks the delete runs (`check_link!`, `check_chain!`): the link's place in the chain, what comes back and goes for each choice, and each choice's refusal now (a schedule on the chain, the link or a delegate that would go, a continue under way, a one-turn run, a moved delegate that can't go back and whether the page can stop it). One session listing walk per call; the page asks only for a chained session as the sheet opens. It takes and releases each link's continue lock (shared, as the delete does), creating its empty file where there was none, and writes nothing else; an unknown id is the usual 404. The moved count is each moved delegate with its subtree (they come back with it), and a `delegate_unmovable` 409 says `stoppable` itself. A stale answer is fine: the delete makes its plan again and refuses as it does. **The whole chain** (`chi sessions delete --chain`, `DELETE /api/sessions/:id/chain`, `SessionManager.delete_chain`): every link reachable from this one on its branch, newest first, each with its delegates by the same rule. Refused before anything goes when a schedule is on the chain (`chain_scheduled`) or on a delegate that would go (`scheduled`), a link or such a delegate is in a one-turn run, a continue of a link is under way (`continuing`), without `force` a link has a worker, or a link's worker outlives the stop's wait: every link is checked and stopped before the first is deleted, and each then goes under the owner locks of it and its delegates. A chain with a gap before this link reaches only the part after the gap: the earlier links stay archived (`cut_off: true`). A link refused part-way (a worker that took it after its stop) leaves it, its delegates and the earlier part of the chain whole, its new end back in the lists, and the result lists what was left.
389
+ - **Deleting a link** (`SessionChain::Delete`; the CLI, the web and `/exit --delete`): a link of a chain is deleted alone by default, and what follows depends on where it is. **The newest link** (nobody continues it, it isn't archived itself, the link before it is archived) undoes its continue: the delegates the continue moved go back to the previous link, finished ones too (`continued_from.json`'s `moved_ids`, still under the link; without the record, its children whose `parent.json` says they came from the previous link), each with a note saying the link was deleted; every note waiting in the link but the continue's own goes back too (`NoteMove.give_back`); then the previous link and what the continue archived with it come back to the lists (without the record, the previous link alone). The previous link is **not started**: reports a moved-back delegate left wait for its next start. What dies with the link: its turns, context sources, objectives edits, session approvals and participant grants (the previous link kept its own copies). Every refusal comes before anything goes: the link's delegates that would go are checked too (a schedule on one, a one-turn run), and they and the link are removed (and the undo runs) only under their `owner.lock`s (kind deleting, taken without waiting, so a worker that took one refuses it); a moved delegate that can't go back (`ChildMove.unmovable`: an older chi's worker, a one-turn run) refuses it (`delegate_unmovable`, naming it), as does a worker that took the link after the stop. Deleting the links one after another undoes each continue by its own record. **A middle link** splits the chain (the earlier links stay archived, the later ones go on as their own chain); nothing is undone or re-linked. A link whose chain is all archived stays archived around the gap. **The link's own delegates** (any position) follow one rule, `SessionChain::Delete::DELEGATES`: a running one (a worker owns it or is starting for it, a one-turn run; a saved `running` with no worker is a crashed run, and goes) is left running with its whole subtree, its file untouched (its parent's id names a deleted session; its reports are refused as for any gone parent); every other node under the link goes, deepest first, before the link. A session in no chain (a link alone past a gap too) is deleted as before. **The web asks first**: for a chained session, chi web's delete sheet reads `GET /api/sessions/:id/delete_plan` (`:owner`; no query or body; no-store), `SessionChain::Delete::Preview` over the same `LinkPlan`/`ChainPlan` and checks the delete runs (`check_link!`, `check_chain!`): the link's place in the chain, what comes back and goes for each choice, and each choice's refusal now (a schedule on the chain, the link or a delegate that would go, a continue under way, a one-turn run, a moved delegate that can't go back and whether the page can stop it). One session listing walk per call; the page asks only for a chained session as the sheet opens. It takes and releases each link's continue lock (shared, as the delete does), creating its empty file where there was none, and writes nothing else; an unknown id is the usual 404. The moved count is each moved delegate with its subtree (they come back with it), and a `delegate_unmovable` 409 says `stoppable` itself. Each choice carries a `digest` (`SessionChain::Delete.digest`: the sorted ids it deletes, leaves, revives and moves back); the sheet's DELETE sends it as `expect=`, and the delete compares it with the plan it runs (a link's under its holds, as `delete_link` starts; the chain's before its checks) and refuses `plan_changed` (409) before anything changes, a session no longer chained too. Without `expect` (the CLI, an older page) it deletes as it plans then. **The whole chain** (`chi sessions delete --chain`, `DELETE /api/sessions/:id/chain`, `SessionManager.delete_chain`): every link reachable from this one on its branch, newest first, each with its delegates by the same rule. Refused before anything goes when a schedule is on the chain (`chain_scheduled`) or on a delegate that would go (`scheduled`), a link or such a delegate is in a one-turn run, a continue of a link is under way (`continuing`), without `force` a link has a worker, or a link's worker outlives the stop's wait: every link is checked and stopped before the first is deleted, and each then goes under the owner locks of it and its delegates. A chain with a gap before this link reaches only the part after the gap: the earlier links stay archived (`cut_off: true`). A link refused part-way (a worker that took it after its stop) leaves it, its delegates and the earlier part of the chain whole, its new end back in the lists, and the result lists what was left.
390
390
 
391
391
  ## Schedules
392
392
 
@@ -551,10 +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
- refuses it at once, before asking, with its pid and `kill -CONT PID`.
562
+ refuses it at once, before asking, with its pid and `kill -CONT PID`. A
563
+ session whose stop is marked (stopped, or its worker being stopped) is refused
564
+ before any of this (`stop_marked`: no successor would come).
565
+ A session being deleted is refused the same way (`deleting`).
560
566
  The web restart route behaves the same way.
data/docs/testing.md CHANGED
@@ -4,7 +4,7 @@
4
4
  bundle exec parallel_rspec -n 8 spec lib/samagotchi/bundles/*/spec # Ruby specs, both roots, in parallel
5
5
  bundle exec rspec spec lib/samagotchi/bundles/*/spec # the same, plain
6
6
  bundle exec rake bundles:specs # the shipped bundles' own specs, on the bundle test kit alone
7
- npm test # web frontend specs
7
+ npm test # web frontend specs, including the new-module exports ratchet
8
8
  npm run lint # web frontend: undefined names and unused imports (ESLint; CI runs it)
9
9
  npm run e2e # web UI happy paths in Chromium, fake model (once: npx playwright install chromium)
10
10
  npx playwright test spec/e2e/stage.spec.js # one e2e file (the root playwright.config.js is the suite's)
@@ -478,7 +478,9 @@ file's layer (any `foo/*.rb` → `spec/foo_golden_spec.rb` when there is one; `t
478
478
  words the attached TUI prints, pick its `event_renderer` and `attached_loop` specs by a rule; `memory_bundle/*.rb`,
479
479
  `bundle_command.rb`, `memory_paths.rb`, `model_overlay.rb` and the corpus's fixtures pick the bundle-state corpus). Changes to `tool_declarations.rb` and `system_prompt.rb` also pick the
480
480
  effective-model, request, prompt-snapshot and full system-prompt goldens because they hash the request's prompt and
481
- tools. Then come the other name matches (a spec named after several changed files first, e.g. `engine_toolkit_spec.rb` for `engine.rb` and
481
+ tools. Changes under `lib/samagotchi/worker/*.rb` also pick `spec/worker_spec.rb`, `spec/worker_*_spec.rb`,
482
+ `spec/web/app_session_settings_characterization_spec.rb` and `spec/require_cycle_spec.rb`. Then come the other name
483
+ matches (a spec named after several changed files first, e.g. `engine_toolkit_spec.rb` for `engine.rb` and
482
484
  `toolkit.rb`; then one beside the file, so `plugin/context.rb` picks `spec/samagotchi/plugin/*context*` before
483
485
  `spec/guardrails/context_spec.rb`), then the specs that name a method the change touches (the innermost `def` around a
484
486
  changed line, read with Prism; one `git grep` for up to 12 names; names under 4 characters, `initialize`, `to_s`,