samagotchi 0.188.0 → 0.190.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 (112) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +76 -1
  3. data/docs/architecture.md +9 -4
  4. data/docs/bundle-authoring.md +1 -1
  5. data/docs/bundles.md +15 -0
  6. data/docs/cli.md +38 -9
  7. data/docs/configuration.md +1 -0
  8. data/docs/guardrails.md +22 -9
  9. data/docs/internals/attached-context.md +4 -1
  10. data/docs/internals/bundles.md +3 -3
  11. data/docs/internals/engine.md +18 -2
  12. data/docs/internals/pages.md +65 -18
  13. data/docs/internals/session-lifecycle.md +19 -6
  14. data/docs/internals/web-frontend.md +3 -3
  15. data/docs/internals/web-push.md +11 -5
  16. data/docs/pages.md +69 -15
  17. data/docs/peers.md +3 -0
  18. data/docs/plugins.md +25 -1
  19. data/docs/releasing.md +1 -1
  20. data/docs/scheduling.md +168 -11
  21. data/docs/sessions.md +4 -4
  22. data/docs/sub-agent.md +1 -1
  23. data/docs/testing.md +1 -1
  24. data/lib/samagotchi/bundle_manifest.rb +34 -5
  25. data/lib/samagotchi/bundles/guardrails/guardrails/rules.yml +15 -0
  26. data/lib/samagotchi/bundles/guardrails/manifest.yml +2 -2
  27. data/lib/samagotchi/bundles/schedules/manifest.yml +11 -0
  28. data/lib/samagotchi/bundles/schedules/scripts/schedules.rb +169 -0
  29. data/lib/samagotchi/bundles/system/manifest.yml +3 -3
  30. data/lib/samagotchi/bundles/system/self_map.md +2 -2
  31. data/lib/samagotchi/bundles/system/skill_pages.md +9 -4
  32. data/lib/samagotchi/config.rb +2 -0
  33. data/lib/samagotchi/context_fetch.rb +9 -3
  34. data/lib/samagotchi/engine/models.rb +6 -4
  35. data/lib/samagotchi/engine/turn_end.rb +20 -2
  36. data/lib/samagotchi/engine.rb +5 -1
  37. data/lib/samagotchi/failure_line.rb +43 -0
  38. data/lib/samagotchi/guardrail_wiring.rb +3 -1
  39. data/lib/samagotchi/guardrails/chi_dirs.rb +20 -5
  40. data/lib/samagotchi/guardrails/parent_approvals.rb +1 -1
  41. data/lib/samagotchi/guardrails/protected_paths.rb +8 -4
  42. data/lib/samagotchi/guardrails/shell_paths.rb +16 -2
  43. data/lib/samagotchi/guardrails/targets.rb +1 -1
  44. data/lib/samagotchi/guardrails/verdict.rb +5 -3
  45. data/lib/samagotchi/image_store.rb +4 -0
  46. data/lib/samagotchi/installed_bundles/manifest.rb +8 -1
  47. data/lib/samagotchi/last_turn.rb +2 -1
  48. data/lib/samagotchi/llm/utf8_scrub.rb +26 -0
  49. data/lib/samagotchi/llm_context_view.rb +6 -0
  50. data/lib/samagotchi/memory_bundle/asset_installer.rb +3 -2
  51. data/lib/samagotchi/memory_bundle/builder.rb +1 -0
  52. data/lib/samagotchi/memory_bundle/installed_copy.rb +1 -1
  53. data/lib/samagotchi/model_profile.rb +4 -1
  54. data/lib/samagotchi/page_command.rb +9 -6
  55. data/lib/samagotchi/pages/bundled.rb +83 -0
  56. data/lib/samagotchi/pages/launch.rb +14 -2
  57. data/lib/samagotchi/pages/runner.rb +7 -2
  58. data/lib/samagotchi/pages/runtime.rb +84 -0
  59. data/lib/samagotchi/pages/store.rb +18 -5
  60. data/lib/samagotchi/pages.rb +47 -3
  61. data/lib/samagotchi/peer_continue.rb +14 -8
  62. data/lib/samagotchi/reply_wait.rb +1 -1
  63. data/lib/samagotchi/run_options.rb +1 -1
  64. data/lib/samagotchi/schedule_command.rb +175 -39
  65. data/lib/samagotchi/schedule_display.rb +85 -0
  66. data/lib/samagotchi/schedules/busy_part.rb +146 -0
  67. data/lib/samagotchi/schedules/condition_part.rb +312 -0
  68. data/lib/samagotchi/schedules/edit_part.rb +144 -0
  69. data/lib/samagotchi/schedules/history_part.rb +51 -0
  70. data/lib/samagotchi/schedules/listing_part.rb +52 -0
  71. data/lib/samagotchi/schedules/notices_part.rb +122 -0
  72. data/lib/samagotchi/schedules/protection_part.rb +113 -0
  73. data/lib/samagotchi/schedules/prune_part.rb +79 -0
  74. data/lib/samagotchi/schedules/recurrence.rb +103 -0
  75. data/lib/samagotchi/schedules.rb +188 -409
  76. data/lib/samagotchi/session_access/local.rb +9 -1
  77. data/lib/samagotchi/session_access/remote.rb +2 -1
  78. data/lib/samagotchi/session_chain/delete.rb +7 -5
  79. data/lib/samagotchi/session_lifecycle/allowed.rb +2 -1
  80. data/lib/samagotchi/session_lifecycle.rb +3 -2
  81. data/lib/samagotchi/session_manager/removal.rb +16 -9
  82. data/lib/samagotchi/session_protection.rb +99 -0
  83. data/lib/samagotchi/session_retention.rb +21 -6
  84. data/lib/samagotchi/sessions_command.rb +4 -0
  85. data/lib/samagotchi/system_one/self_protect.rb +4 -2
  86. data/lib/samagotchi/testing/boundary.rb +13 -0
  87. data/lib/samagotchi/tools/cancel_schedule.rb +32 -4
  88. data/lib/samagotchi/tools/execute.rb +5 -1
  89. data/lib/samagotchi/tools/list_schedules.rb +1 -0
  90. data/lib/samagotchi/tools/task_runtime.rb +6 -0
  91. data/lib/samagotchi/turn_endings.rb +14 -2
  92. data/lib/samagotchi/turn_flow.rb +2 -1
  93. data/lib/samagotchi/turn_outcome.rb +41 -0
  94. data/lib/samagotchi/version.rb +1 -1
  95. data/lib/samagotchi/web/page_routes.rb +13 -8
  96. data/lib/samagotchi/web/public/app.js +12 -18
  97. data/lib/samagotchi/web/public/index.html +11 -2
  98. data/lib/samagotchi/web/public/owner_claim.js +7 -5
  99. data/lib/samagotchi/web/public/page_links.js +1 -1
  100. data/lib/samagotchi/web/public/page_view.js +8 -5
  101. data/lib/samagotchi/web/public/pages.css +9 -2
  102. data/lib/samagotchi/web/public/pages_group.js +21 -19
  103. data/lib/samagotchi/web/public/pages_list.js +73 -0
  104. data/lib/samagotchi/web/public/pages_model.js +54 -0
  105. data/lib/samagotchi/web/public/pages_wiring.js +66 -0
  106. data/lib/samagotchi/web/public/stream_handlers.js +8 -0
  107. data/lib/samagotchi/web/public/views.js +77 -23
  108. data/lib/samagotchi/web/push/notifier.rb +4 -3
  109. data/lib/samagotchi/web/server.rb +3 -1
  110. data/lib/samagotchi/web/session_hub.rb +75 -19
  111. data/lib/samagotchi/worker.rb +6 -4
  112. metadata +20 -1
data/docs/scheduling.md CHANGED
@@ -19,8 +19,9 @@ against, never rewritten: the chain's root and the id you remember), `head` (the
19
19
  chain's current link, re-anchored after every firing: the link a chain continue
20
20
  made, or the session a `same` turn was queued into), `mode`,
21
21
  `prompt`, `recurrence`, `catch_up`, `keep_links`, `max_failures`, `max_skips`,
22
- `next_due` (UTC ISO), `last_fired`, `last_result`, `failures`, `skips` and
23
- `enabled`.
22
+ `next_due` (UTC ISO), `last_fired`, `last_result`, `failures`, `skips`,
23
+ `enabled` and `condition` (your `--if CMD`, [Conditions](#conditions---if); `null` for
24
+ none).
24
25
 
25
26
  <a id="reminder-vs-schedule"></a>## Reminder or schedule?
26
27
 
@@ -105,7 +106,11 @@ time zones.
105
106
 
106
107
  ## The busy check
107
108
 
108
- A cron tick cannot read a worker's memory, so the tick has two paths.
109
+ A cron tick cannot read a worker's memory, so the tick has two paths. What the
110
+ session's lifecycle state answers (deleting, stopped, a worker starting, leaving or
111
+ on a newer chi) comes from the lifecycle table (`SessionLifecycle::ALLOWED`,
112
+ [internals](internals/session-lifecycle.md)); the Bridge ask and the file checks
113
+ below are the busy check's own.
109
114
 
110
115
  **Being deleted** (a deleter holds the owner lock) comes before a stop marker.
111
116
  The skip is "the session is being deleted", and the next tick finds the session
@@ -197,6 +202,29 @@ tick is about an hour of patience, which is what the count really measures.
197
202
  `chi schedule enable` resets both counters too: a schedule turned back on gets its
198
203
  whole budget again, not one skip.
199
204
 
205
+ `chi schedule show ID` ends with the entry's last 20 outcomes, newest first, one
206
+ line each in local time: `fired`, `skipped`, `failed`, `missed`, your `enabled` and
207
+ `disabled`, a `chi schedule edit`'s `edited` (naming the fields), with the reason and
208
+ the session it acted on (a skip or
209
+ failure that used up the budget says `disabled: <reason>`). `list --format json` has
210
+ them as each entry's `history` (and an unpushed turn-off as `disabled_notice`).
211
+
212
+ `list --format json` gives each entry every stored field (with any key a newer chi
213
+ added), then `recurrence_words`, `skip_window`, and what a reader would otherwise work
214
+ out: `name` (the title, or the start of the prompt in quotes, as `list` names it),
215
+ `state` (`on`, `firing` while a firing is in flight, `off`) and `off_reason`, why an
216
+ off one is off: `owner` (your `disable`), `skips` or `failures` (a budget used up),
217
+ and for a `date` one-off its last outcome in the history: `done` (it fired),
218
+ `failures` (it failed) or `missed`; `off` when none of these says (an older file's
219
+ spent one-off). These come last, so a stored key of the same name never hides them
220
+ (`ScheduleDisplay.json`).
221
+
222
+ `chi schedule edit ID` changes a schedule in place (its title, prompt, recurrence,
223
+ catch-up or budgets; [CLI](cli.md#durable-schedules-chi-schedule)) and keeps its id,
224
+ session, mode, counters and history. A new recurrence starts its clock at the edit, as
225
+ an `add`'s does, and waits for a firing in flight to settle; a spent `date` one-off
226
+ stays disabled after an edit until you `enable` it.
227
+
200
228
  A recurring schedule the owner has disabled stays off when an in-flight skip or
201
229
  failure is recorded. A `date` one-off is the exception: a skip or failure puts its
202
230
  moment back and re-enables it. `run-now` still tries a disabled schedule, but a
@@ -204,13 +232,20 @@ refusal records its result without moving the skip or failure counters.
204
232
 
205
233
  The tick line that disabled an entry ends `(disabled)` (`chi schedule tick`,
206
234
  `run-now`), and `tick --format json` gives that outcome `"disabled": true`
207
- (`Schedules::Outcome#disabled`). When **chi web's** tick (`schedule.auto_tick`)
208
- disables a recurring schedule, the phone gets one notification
235
+ (`Schedules::Outcome#disabled`). When any tick — chi web's own (`schedule.auto_tick`),
236
+ a cron `chi schedule tick` or a `chi schedule run-now` — disables a recurring schedule
237
+ by its budget, the phone gets one notification
209
238
  ([Phone notifications](configuration.md#phone-notifications-web-push)): "Schedule
210
239
  disabled: Heartbeat", "skipped 12 times: <the last reason>" and the `chi schedule
211
- enable <id>` that turns it back on; a tap opens its session. It shows even with a chi
212
- web page in front and waits a day for a phone that is offline. Nothing notifies for a
213
- cron tick or `chi schedule run-now` (only chi web pushes), a `--dry-run`, your own
240
+ enable <id>` that turns it back on; a tap opens its session. The tick leaves a notice
241
+ on the entry in `schedules.json` (`disabled_notice`) and a running chi web pushes it:
242
+ right after its own tick, and within `schedule.tick_interval_minutes` for another
243
+ ticker's, with `schedule.auto_tick` off too (a look that finds a tick holding the lock
244
+ tries again at the next scan, not an interval later). Only chi web pushes, so with no chi web
245
+ running the notice waits for one; a notice more than a day old, or one whose schedule
246
+ you enabled again, is dropped unpushed, and `chi schedule enable` clears it. It shows
247
+ even with a chi web page in front and waits a day for a phone that is offline. Two chi
248
+ webs on one state dir push it once. Nothing notifies for a `--dry-run`, your own
214
249
  `chi schedule disable`, or a `date` one-off (spent when it fires; one that then fails
215
250
  stays disabled with the failure in `chi schedule list`).
216
251
 
@@ -222,7 +257,9 @@ and `show`. A question does not time out with the 40-second firing step: the tur
222
257
  stays pending until its hard limit, derived from the schedule interval (at least
223
258
  10 minutes and at most 6 hours). If no outcome is known by then, it counts as a
224
259
  failure with reason `no outcome`. Failed, canceled and expired turns are not
225
- re-fired; `next_due` remains at the next occurrence.
260
+ re-fired; `next_due` remains at the next occurrence. The turn's outcome is read
261
+ from its files by `TurnOutcome.for` (`turn_outcome.rb`: its reply, its settled turn and
262
+ the words); `Schedules#resolve_pending` keeps the order: the reply, the question, the turn, expiry.
226
263
 
227
264
  A chain holds at most `schedule.max_per_session` enabled schedules (default 10) and
228
265
  the machine `schedule.max_total` (default 50); `schedule_task` and `chi schedule add`
@@ -231,7 +268,10 @@ and recurrence, or the same title — is refused too, naming its id, so a routin
231
268
  tells each of its links to "make sure the Monday audit is scheduled" cannot multiply
232
269
  itself. `schedule_task`, `list_schedules` and `cancel_schedule` see only schedules of
233
270
  the calling session's chain (`all: true` steps outside it); `chi schedule list` is
234
- always the machine-wide view. An id, prefix or title that matches more than one entry
271
+ always the machine-wide view. An entry that doesn't read (`list` counts it, "chi schedule
272
+ cancel ID removes one") is cancelled by its exact id with `chi schedule cancel ID`, and by
273
+ `cancel_schedule` when its stored `anchor` or `head` is a link of the chain; one with
274
+ neither (its chain can't be told) only with `all: true`. An id, prefix or title that matches more than one entry
235
275
  is refused with exit 2, naming the matches.
236
276
 
237
277
  The tick's lock covers the file only, never the action: the clock advances before
@@ -248,6 +288,95 @@ And a `chi schedule add` from a terminal never waits on an archive or a recap wa
248
288
  own retry loop follows a continue a human made between our resolve and its lock
249
289
  instead of racing it.
250
290
 
291
+ ## Conditions (`--if`)
292
+
293
+ `chi schedule add … --if CMD` (and `chi schedule edit ID --if CMD`, `--no-if` to drop
294
+ it) gates a schedule on a shell command: at each due tick chi runs CMD first, and the
295
+ firing happens only when CMD says it is needed. A heartbeat, say, a chain firing every
296
+ few minutes, can ask "is there anything to do?" first, so that most ticks cost no model
297
+ turn.
298
+
299
+ ```
300
+ chi schedule add --session ab12 --every 5m -m "Check in" --if "$HOME/.local/bin/anything-to-do"
301
+ ```
302
+
303
+ What the exit status means:
304
+
305
+ | CMD | the tick |
306
+ |---|---|
307
+ | exits 0 | goes on as without a condition: the busy check, then the firing |
308
+ | exits 1 to 125 | **not needed**: `next_due` moves to the next occurrence, `last_result` is `not needed: exit N: <its first line of stdout, else its last of stderr>`, the tick prints `not-needed`; nothing else changes (no skip or failure counted, no history row, the chain's one firing per tick left to its other schedules) |
309
+ | exits 126 or 127 (not executable, not found), dies by a signal, runs past `schedule.condition_timeout_seconds` (default 30, at most 300), prints more than 1 MiB, or can't start (the session's folder is gone) | a **failure** (`condition: <why>`), counted toward `max_failures` like any other, the occurrence kept for the next tick: a broken condition turns the schedule off after 3 ticks (about 15 minutes at a 5 minute tick), with the phone notification. Failures reset only when the schedule fires (or you enable it): a gate that seldom says yes adds up errors that come days apart, and three of them turn it off |
310
+
311
+ The order, per due schedule with a condition: its target resolves (a gone or archived
312
+ one fails as without a condition), then `catch_up: none` a whole cycle late is
313
+ `missed`, then the condition's answer, then the busy check. So a busy target spends no
314
+ skip on an occurrence that wasn't needed.
315
+
316
+ How it runs: `sh -c CMD` in the target session's folder, in its own process group
317
+ (a timeout kills the whole group), stdin closed, with the ticker's environment
318
+ scrubbed of Ruby's and Bundler's variables (`SpawnEnv`), plus
319
+ `SAMAGOTCHI_SCHEDULE_ID`, `SAMAGOTCHI_SCHEDULE_TITLE` and `SAMAGOTCHI_SCHEDULE_SESSION`
320
+ (the session it acts on) and never `SAMAGOTCHI_PARENT_SESSION`. Treat the title (and the
321
+ session id) as untrusted input in a gate script: the model may change a schedule's title
322
+ (`chi schedule edit --title` isn't owner-only), so quote it and never `eval` it. It gets the ticker's
323
+ environment: cron's PATH is thin, so name commands by absolute path, and the project's
324
+ mise tools aren't set up (wrap CMD in `mise exec --` when it needs them). It inherits
325
+ what the ticker's environment holds, secrets included. Each due condition runs once, in
326
+ turn, before the tick takes the schedule lock (a slow CMD never holds `chi schedule
327
+ add` or a firing's record up), and the tick's clock moves on by the time they took.
328
+ When the lock is taken, an answer counts only for the condition, the `next_due` and the
329
+ failure count it ran for (so two tickers count one occurrence's error once): an edit, a run-now or another ticker in between leaves the schedule as it is
330
+ and the next tick asks again. So CMD should be cheap, read-only and safe to run twice
331
+ (cron and chi web ticking at once may both run it). A schedule whose target is busy
332
+ runs CMD at every tick until it fires.
333
+
334
+ `chi schedule run-now` fires without asking CMD; `tick --dry-run` doesn't run it
335
+ (`would fire every 5m · if CMD (not run)`). `chi schedule show` has it as `if: CMD
336
+ (set from the CLI <time>; timeout 30 s; run-now skips it)`, `list` adds ` if: CMD`, and
337
+ `list --format json` gives `condition` as `{cmd, by, set_at}`. A `--date` one-off takes
338
+ none (it fires once; edit it to `--every` or `--weekday` first); one that has one anyway
339
+ (an older chi's `edit --date`) fails each tick, "conditions don't apply to a one-off",
340
+ without running CMD, until its budget turns it off.
341
+
342
+ **Only you set one.** CMD runs unattended and outside the
343
+ [guardrails](guardrails.md), so a condition is the owner's alone:
344
+ - `chi schedule … --if` / `--no-if` inside a chi session (any agent's shell:
345
+ `SAMAGOTCHI_PARENT_SESSION` is set) exits 2: "a schedule's condition is set only
346
+ from your own terminal";
347
+ - the `schedule_task` tool has no condition (and `list_schedules` only shows it);
348
+ - with the guardrails bundle, a shell command that runs `chi schedule add|edit … --if`
349
+ asks you every time (`chi-schedule-if`: no parent agent and no System 1 may allow
350
+ it), and `schedules.json` is a protected path: chi's file tools can't write it
351
+ (`chi-schedules`), and a shell command naming it asks (`shell-touches-chi`).
352
+ These are an accident guard, not a sandbox (chi's guardrails are for a model you trust
353
+ not to try): the in-session refusal and the user-only rule stop an accidental or casual
354
+ set, not a determined evasion. A command that unsets the session marker (`env -u
355
+ SAMAGOTCHI_PARENT_SESSION`) and spells the flag so the rule's text doesn't see it (quoting
356
+ or a backslash inside `--if`, a variable) gets through, as it does for `chi context add
357
+ --cmd`; so does a script that edits the file without naming it. A page script runs
358
+ without the session markers too ([pages.md](pages.md): a page is code you trust), so a
359
+ model-written page that runs `chi schedule … --if` sets one when you open it. Keep CMD itself out of the model's reach too: a gate script
360
+ inside a project the model edits is one it can change, and the tick then runs what the
361
+ model wrote. `add` and `edit --if` warn when CMD's first word is a relative path (it
362
+ resolves in the session's folder) or a script inside the session's folder or any git
363
+ work tree: "warning: the model can edit this script; keep a gate outside your projects
364
+ (an absolute path, e.g. under ~/.local/bin)". It is a warning, not a refusal; a command
365
+ on PATH (`test -f …`, `gh …`) gets none.
366
+
367
+ **Every ticker must be new enough.** A chi of 0.189.0 or older (0.189.0 shipped without them) doesn't know
368
+ conditions and would fire such a schedule unasked, so chi stores a schedule with a
369
+ condition with `next_due: null` and the real time under `condition_next_due`: an older
370
+ chi never finds it due (it reads it, lists it with no next time, keeps its sessions
371
+ from retention, and enables, disables and cancels it), and a newer one reads the real
372
+ time back. `add` and `edit --if` say so: "every chi that ticks (chi web, cron) must be
373
+ newer than 0.189.0; an older one leaves this schedule alone". After updating chi,
374
+ restart chi web and point cron at the new chi, or the schedule waits. One leak remains:
375
+ an older chi's `run-now`, or its `edit` of the recurrence, writes a real `next_due`,
376
+ and an older ticker then fires the schedule unconditionally until a newer chi writes
377
+ the file again (one tick in a mixed setup). A condition set by anything but the CLI
378
+ (`by` other than `cli`, a later chi's) fails closed: counted as a failure, never run.
379
+
251
380
  ## Keeping the chain short
252
381
 
253
382
  `keep_links` (default `schedule.default_keep_links`, `0` keeps all) is how many
@@ -267,6 +396,17 @@ its descendants, and archived sessions are outside the retention sweep
267
396
  count. The `anchor` is never pruned: it is the chain's root, the id the user and
268
397
  the coordinator remember, and `last:<anchor>` must keep resolving.
269
398
 
399
+ What a schedule protects (its anchor, its head and its resolved target, while it is
400
+ enabled) the retention sweep keeps and a delete refuses: schedules are
401
+ `SessionProtection`'s one protector (`Schedules::ProtectionPart`, [sessions.md](sessions.md)). It reads
402
+ `schedules.json` strictly: a file that is there but doesn't read (not JSON, a `schedules` member that isn't a list, a
403
+ file chi can't open) makes the sweep delete nothing that round (`retention_skipped`, retried at the next sweep
404
+ interval) and every delete refused, "schedules.json is unreadable (…): fix or remove it before deleting sessions". One
405
+ schedule that doesn't read does the same in its own words, "schedule entry <id> in schedules.json is unreadable
406
+ (lacks prompt): chi schedule cancel <id>, or fix the file, before deleting sessions": `chi schedule cancel <id>` removes
407
+ such a record by its id (`list` doesn't show it). The tick keeps its own rule (it refuses a file that isn't JSON and
408
+ skips a schedule that doesn't read).
409
+
270
410
  Schedule prune leaves the deleted links' background tasks running: a later link
271
411
  may still use a server started by an earlier link in the same project. Continue
272
412
  does not yet transfer task ownership.
@@ -303,7 +443,8 @@ Run it from systemd or launchd instead if you prefer a timer: the command is the
303
443
  same, `chi schedule tick`, and the lock makes overlapping runs harmless — the
304
444
  second one exits 0 with "no schedules due (another tick holds the lock)".
305
445
  `--dry-run` prints what would fire and changes nothing; `--format json` is the seam
306
- for scripts and for a future web UI. `chi schedule run-now` reserves the entry
446
+ for scripts; a page script reads the schedules in chi itself instead
447
+ (`runtime.schedules`, [pages.md](pages.md#reading-chis-data-runtime)). `chi schedule run-now` reserves the entry
307
448
  under the same lock before starting its action, so it cannot race a tick into a
308
449
  duplicate firing.
309
450
 
@@ -327,5 +468,21 @@ the configured interval, `chi schedule add`, `chi schedule list` and `schedule_t
327
468
  warn to turn `schedule.auto_tick` on or run `chi schedule tick` from cron; `--dry-run`
328
469
  and lock-held attempts do not refresh `last_tick_at`.
329
470
 
471
+ ## The Schedules page
472
+
473
+ `chi bundle install schedules` adds a **Schedules** page to chi web (`#/p/schedules`,
474
+ under the `pages` pill; `chi page run schedules` in a terminal) from the shipped
475
+ schedules bundle ([bundles.md](bundles.md#the-schedules-bundle)). It shows how many
476
+ schedules there are and in which state, with the tick warning when nothing ticks; each
477
+ schedule that is off and why ("turned off by you", "skipped 12 times (≈1 h at a 5 min
478
+ tick): busy", "failed 3 times: …", "one-off, done") with the `chi schedule enable ID`
479
+ that turns it back on (for a spent one-off, which has no next time, a `chi schedule
480
+ edit ID --date …` first); each entry of `schedules.json` that can't be read with the
481
+ `chi schedule cancel ID` that removes it; a table of every schedule (its If column the `--if` command; on and firing
482
+ first by next due, those with none last, then off; times in this machine's zone) and the recent runs, newest
483
+ first. It is read-only: ask chi, or use `chi schedule`, to change one. What it shows is
484
+ as of its last run: Refresh to update. A `schedules.json` that isn't JSON fails the
485
+ run with the store's own words, and the last good result stays.
486
+
330
487
  See [cli.md](cli.md) for the subcommands and flags, and
331
488
  [configuration.md](configuration.md) for the `schedule.*` settings.
data/docs/sessions.md CHANGED
@@ -31,7 +31,7 @@ unread messages reach the new link as one note); a delete removes them. See
31
31
  | `SAMAGOTCHI_SESSION_KEEP_STATUS` | (none) | CSV of statuses never auto-pruned |
32
32
  | `SAMAGOTCHI_SESSION_SWEEP_INTERVAL_HOURS` | `24` | Throttle lazy sweep |
33
33
 
34
- A session is deleted if **expired by age OR overflow by count** (unless `keep_status` or the live-owner guard: a session a worker or `chi` still has open is never pruned). A session's `status` is its turn state (`idle`/`running`), not whether a worker is alive. Orphan dirs without a `*.json` are never deleted, except skeleton-only ones (see *Empty sessions*). Deletion removes its `*.json` and sidecar dir under the deleting owner lock, along with its plugin state, attached context, participant grants, System 1 runs and context-candidate records. Explicit delete and retention use the same cleanup path. Set both `DAYS=0` and `MAX=0` to retain forever.
34
+ A session is deleted if **expired by age OR overflow by count** (unless `keep_status` or the live-owner guard: a session a worker or `chi` still has open is never pruned). A session's `status` is its turn state (`idle`/`running`), not whether a worker is alive. Orphan dirs without a `*.json` are never deleted, except skeleton-only ones (see *Empty sessions*). Deletion removes its `*.json` and sidecar dir under the deleting owner lock, along with its plugin state, attached context, participant grants, System 1 runs and context-candidate records. Explicit delete and retention use the same cleanup path. Set both `DAYS=0` and `MAX=0` to retain forever. A session something protects is kept whatever its age or place: an enabled schedule's anchor, head and resolved target (`SessionProtection.protected_ids`; schedules are its one protector, *Deleting a session*). A protector that can't answer stops the sweep's deletes for that round: a `schedules.json` that is there but doesn't read (not JSON, not a schedules document, a file chi can't open, or a schedule in it that doesn't read) protects everyone until it is fixed (one `retention_skipped` line per sweep interval, the next try at the next interval; the skeleton-only dirs and saved runs are still swept), and `chi sessions prune`/`clean` exit 1 with its words; a missing one is no schedules ([scheduling.md](scheduling.md#keeping-the-chain-short): `chi schedule cancel <id>` removes one schedule that doesn't read).
35
35
 
36
36
  Retention and manual prune/clean silently stop each deleted session's verified background tasks under its deleting lock, with `by: retention` (`stopped_by_retention`). Sessions are processed sequentially, their tasks in parallel. Unverified or unreadable tasks are not signalled; stops and failures are logged per task as `retention_task_stopped` / `retention_task_not_stopped`, without commands. A scratch session's own cleanup does the same with `by: scratch` and `scratch_task_stopped` / `scratch_task_not_stopped`.
37
37
 
@@ -55,7 +55,7 @@ A new session field is one `Session::FIELDS` row, plus a `SessionSetup` member w
55
55
 
56
56
  **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.
57
57
 
58
- **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 asks in one sheet first (*Session chains* → Deleting a link, the page side in docs/internals/web-frontend.md, The delete sheet): what goes, what is stopped first and what stays, one button naming the outcome, no browser confirm. 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`) goes through `SessionChain::Delete.link` for every session, chained or not (*Session chains* → Deleting a link): **its delegates follow one rule** (`SessionManager::DELEGATES`): the stopped ones (archived ones too) go with it, deepest first, and a running one stays with its whole subtree, its file untouched; a stopped delegate with a running child goes and leaves that child without a parent. The delegates that would go bring their own refusals: one that is a schedule's target, anchor or head refuses the delete (`scheduled`, naming the delegate), as does one in a one-turn run, one a worker took after the plan was made (`worker_running`), and their running background tasks (below); their participant grants end with them. The result lists them in `deleted` (the session last) and the running ones with their subtrees in `left_running`; the CLI's line and `/exit --delete` say how many went. It is also 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 (`delete_resolved`: they pass neither keyword and take no delegates); 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; with `&tasks=<id,id>`, the ones the sheet named, only those: `RunningTasks::Policy.stop(only:)`, see *Deleting a link*) 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_workers}` (`stopped_worker`: whose worker the delete stopped before the last check refused; `stopped_workers`: every worker the delete stopped), each task `{session_id, id, command}` (`links` too for a chain delete's other links); the 200 gains `tasks_stopped`, `tasks_not_stopped` and `tasks_ended` (empty unless stopped). A session's file gone (its folder left) has no tasks. The retention sweep and scratch cleanup stop verified tasks silently; the empty-session discard, failed-continue rollback and schedule prune leave them running.
58
+ **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 asks in one sheet first (*Session chains* → Deleting a link, the page side in docs/internals/web-frontend.md, The delete sheet): what goes, what is stopped first and what stays, one button naming the outcome, no browser confirm. 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. Who refuses a delete is one question, `SessionProtection` (`session_protection.rb`, beside `SessionStores`, which says what a delete removes): every protector in `PROTECTORS` is asked (`hold` for a session, `chain_hold` for a chain, `protected_ids` for retention), schedules the one there is (`Schedules::ProtectionPart`), and the first hold is the refusal (`SessionManager.refuse_protected!`, `DeleteRefused` with the hold's reason and its `schedule_id`). It fails closed: a protector that raises is logged (`protector_failed`) and the error raised, so nothing is deleted; a store that is there but doesn't read (`SessionProtection::Unreadable`) refuses every delete, `protection_unreadable`, "schedules.json is unreadable (…): fix or remove it before deleting sessions" (the delete sheet shows it as the choice's refusal). An archive asks no protector. A user's delete (these three, `revive_previous:` and `refuse_continuing:` on `delete_session`) goes through `SessionChain::Delete.link` for every session, chained or not (*Session chains* → Deleting a link): **its delegates follow one rule** (`SessionManager::DELEGATES`): the stopped ones (archived ones too) go with it, deepest first, and a running one stays with its whole subtree, its file untouched; a stopped delegate with a running child goes and leaves that child without a parent. The delegates that would go bring their own refusals: one that is a schedule's target, anchor or head refuses the delete (`scheduled`, naming the delegate), as does one in a one-turn run, one a worker took after the plan was made (`worker_running`), and their running background tasks (below); their participant grants end with them. The result lists them in `deleted` (the session last) and the running ones with their subtrees in `left_running`; the CLI's line and `/exit --delete` say how many went. It is also 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 (`delete_resolved`: they pass neither keyword and take no delegates); 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; with `&tasks=<id,id>`, the ones the sheet named, only those: `RunningTasks::Policy.stop(only:)`, see *Deleting a link*) 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_workers}` (`stopped_worker`: whose worker the delete stopped before the last check refused; `stopped_workers`: every worker the delete stopped), each task `{session_id, id, command}` (`links` too for a chain delete's other links); the 200 gains `tasks_stopped`, `tasks_not_stopped` and `tasks_ended` (empty unless stopped). A session's file gone (its folder left) has no tasks. The retention sweep and scratch cleanup stop verified tasks silently; the empty-session discard, failed-continue rollback and schedule prune leave them running.
59
59
 
60
60
  <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"`. The web's Archive stays one tap (the toast's Undo) when nothing is in the way; its 409 opens the delete sheet in Archive's words (what is hidden, the tasks it stops first, `Stop them and archive`, which sends the tasks it named), and any other refusal is that sheet's "Can't archive … now". The 409 also says `sessions`: how many sessions the archive would hide (it and its delegates, across every project), plus `stopped_workers` (every stopped worker id). The refusal words name one stopped worker as "its worker was stopped" or "9d0e1f2a's worker was stopped", and several as "N workers were stopped: its own, 9d0e1f2a". `chi sessions archive --stop-tasks`, or the archive route's body `{"stop_tasks": true}` (with `"tasks": [ids]` only those; a running one not named refuses, `tasks_running`, nothing archived: up front before any worker is stopped, and again after the workers let go), 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.
61
61
 
@@ -408,8 +408,8 @@ A session can **continue** an earlier one: "the next run of the same routine" (a
408
408
  - **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.
409
409
  - **CLI:** `chi send --new --continues (ID|PREFIX|last:ID) [--model M] [-m TEXT]` (see *Starting a session*).
410
410
  - **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.
411
- - **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, `SessionManager::DELEGATES` (`SessionManager::DelegateRule`; one shared preview row snapshot): 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 a link with nothing to undo: its delegates follow the same rule (*Deleting a session*). **The web asks first**: chi web's delete sheet reads `GET /api/sessions/:id/delete_plan` (`:owner`; no query or body; no-store) for any session, `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). A session in no chain answers `{chained: false, session_id, link}`, the same `link` a chained one gets (`previous_id` null, `earlier`/`later` 0, `next_id` null); an older page reads only `chained`. Each choice (`link`, `chain`) also carries `delegates` (`{delete: [ids], leave: [{id, running}]}`; `running` false for a stopped session left under a running delegate, beside the counts `deletes` and `left_running`), `tasks` (`{running, unverified, unreadable}`: `RunningTasks.of` the ids the choice deletes) and `worker` (a link's: `"turn"` when a worker owns it and a turn runs, `"idle"` when a worker owns it or is starting, null; a chain's `{idle, turn}` counts over its links). No titles: the page names each id from its own list. One shared session-row snapshot serves the link and chain choices; Links lists on its own, and a folder whose session file is gone answers too (the delete still takes it). Each call read-only checks each link's continue lock (a session in no chain too), and writes nothing else but the listing's own repair of an interrupted continue; an unknown id is the usual 404. chi web lists `delete_plan_all` in `/api/info`'s features (`Web::App::DELETE_PLAN_FEATURE`). **The tap stops only what the sheet named**: whenever the choice lists any task, the page sends `stop_tasks=true&tasks=<id,id>`, the choice's running ids (`tasks=` when it has only unverified or unreadable records, which a stop never signals, so such a session can still be deleted); archive's sheet sends `{"stop_tasks": true, "tasks": [ids]}` in its body. `tasks` works only with `stop_tasks`; without it, it is ignored, and `stop_tasks` without `tasks` (the CLI's `--stop-tasks`, an older page) takes every running task the operation can stop. A running task not named refuses (`tasks_running`), and the sheet reads the plan again and shows it with "changed; check again". A chain stops link by link: a link refused that way leaves it and the earlier links whole. 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 in no chain is compared the same way (a sheet shown for a link whose chain is gone since deletes when its ids still match). Without `expect` (the CLI, an older page) it deletes as it plans then.
412
- **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.
411
+ - **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 through `SessionProtection.hold`, 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, `SessionManager::DELEGATES` (`SessionManager::DelegateRule`; one shared preview row snapshot): 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 a link with nothing to undo: its delegates follow the same rule (*Deleting a session*). **The web asks first**: chi web's delete sheet reads `GET /api/sessions/:id/delete_plan` (`:owner`; no query or body; no-store) for any session, `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). A session in no chain answers `{chained: false, session_id, link}`, the same `link` a chained one gets (`previous_id` null, `earlier`/`later` 0, `next_id` null); an older page reads only `chained`. Each choice (`link`, `chain`) also carries `delegates` (`{delete: [ids], leave: [{id, running}]}`; `running` false for a stopped session left under a running delegate, beside the counts `deletes` and `left_running`), `tasks` (`{running, unverified, unreadable}`: `RunningTasks.of` the ids the choice deletes) and `worker` (a link's: `"turn"` when a worker owns it and a turn runs, `"idle"` when a worker owns it or is starting, null; a chain's `{idle, turn}` counts over its links). No titles: the page names each id from its own list. One shared session-row snapshot serves the link and chain choices; Links lists on its own, and a folder whose session file is gone answers too (the delete still takes it). Each call read-only checks each link's continue lock (a session in no chain too), and writes nothing else but the listing's own repair of an interrupted continue; an unknown id is the usual 404. chi web lists `delete_plan_all` in `/api/info`'s features (`Web::App::DELETE_PLAN_FEATURE`). **The tap stops only what the sheet named**: whenever the choice lists any task, the page sends `stop_tasks=true&tasks=<id,id>`, the choice's running ids (`tasks=` when it has only unverified or unreadable records, which a stop never signals, so such a session can still be deleted); archive's sheet sends `{"stop_tasks": true, "tasks": [ids]}` in its body. `tasks` works only with `stop_tasks`; without it, it is ignored, and `stop_tasks` without `tasks` (the CLI's `--stop-tasks`, an older page) takes every running task the operation can stop. A running task not named refuses (`tasks_running`), and the sheet reads the plan again and shows it with "changed; check again". A chain stops link by link: a link refused that way leaves it and the earlier links whole. 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 in no chain is compared the same way (a sheet shown for a link whose chain is gone since deletes when its ids still match). Without `expect` (the CLI, an older page) it deletes as it plans then.
412
+ **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`, `SessionProtection.chain_hold`) 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.
413
413
 
414
414
  ## Schedules
415
415
 
data/docs/sub-agent.md CHANGED
@@ -126,7 +126,7 @@ Exit codes, both commands:
126
126
  | 3 | `waiting_for_owner` | (a participant's wait, `chi --remote NAME send --wait` with their link's token) their turn waits on the session's owner: a question or an approval it raised, or the owner's step-limit Continue; wait again |
127
127
  | 4 | `running` | `--timeout` passed; the turn goes on, wait again |
128
128
  | 1 | `refused` | the queued turn was refused before it ran, no turn ran for it: `cancel_reason` `max_wakes` (an agent's message as a visitor, past `session.max_wakes`: [driver and visitor](#an-agents-messages-driver-and-visitor)), or for a participant's wait `revoked` (their link was revoked or expired), `outdated` (their link is an older chi's read-only one) or `cap_reached` (they spent their cap) |
129
- | 1 | `failed`, `canceled`, `limit`, `removed`, `no_answer`, `error`, `worker_gone`, `stopped` | `detail` says what happened (`limit`: the turn ran out of steps and nobody can be asked, e.g. an older worker; `chi send ID -m '/continue yes'` continues it, except under `guardrails.parent_answers: hard`, where a parent's `/continue yes` is refused as its `chi answer --option Continue` is; `removed`: the `--queue` message waited for was taken back before it ran, no turn ran for it). `failed` adds `error_kind` (the provider error's kind: `credits`, `credits_held`, `rate_limited`, `server`, `auth`, `connection`, …) and `retryable` when known; `canceled` adds `cancel_reason` (`user`: a Stop in the web; `session_stopped`: a session stop, `chi sessions stop` or the web's; `worker_stopped`: the turn waited for (a `--queue` message's, a message's to an idle session, the running turn a message merged into or a plain `--wait` saw running) died with its worker (detail "its worker exited mid-turn"), settled by the next one; `hook`; `ctrl_c`; `manual`) and `stopped_by` (the hook that stopped it, e.g. `loop-guard`) when known |
129
+ | 1 | `failed`, `canceled`, `limit`, `removed`, `no_answer`, `error`, `worker_gone`, `stopped` | `detail` says what happened (`limit`: the turn ran out of steps and nobody can be asked, e.g. an older worker; `chi send ID -m '/continue yes'` continues it, except under `guardrails.parent_answers: hard`, where a parent's `/continue yes` is refused as its `chi answer --option Continue` is; `removed`: the `--queue` message waited for was taken back before it ran, no turn ran for it). `failed` adds `error_kind` (the provider error's kind: `credits`, `credits_held`, `rate_limited`, `server`, `auth`, `connection`, …; `chi_error` when chi itself failed, see samagotchi.log) and `retryable` when known; `canceled` adds `cancel_reason` (`user`: a Stop in the web; `session_stopped`: a session stop, `chi sessions stop` or the web's; `worker_stopped`: the turn waited for (a `--queue` message's, a message's to an idle session, the running turn a message merged into or a plain `--wait` saw running) died with its worker (detail "its worker exited mid-turn"), settled by the next one; `hook`; `ctrl_c`; `manual`) and `stopped_by` (the hook that stopped it, e.g. `loop-guard`) when known |
130
130
  | 2 | (no JSON) | usage error, or an option the question doesn't offer |
131
131
  | 130 | `running` | Ctrl-C; the turn goes on |
132
132
 
data/docs/testing.md CHANGED
@@ -683,7 +683,7 @@ that reopens the namespace and nothing else does (then firing the autoload loads
683
683
  four kinds: a part naming its host's value constants (`Samagotchi::Engine::[A-Z][A-Z_]*` in
684
684
  `engine/*.rb`: the host requires the part, so a require back is a cycle; the glob leaves classes a part
685
685
  names from elsewhere checked), one-off host pairs (`ToolRun` in `tool_response.rb`), the namespace
686
- autoloads that load whole (`SessionManager`, `Objectives`, `Config`), and `Plugin::Http`'s (its base file
686
+ autoloads that load whole (`SessionManager`, `Objectives`, `Config`, `Schedules`), and `Plugin::Http`'s (its base file
687
687
  loads the reopening file only inside a method, and that file requires the base file first). The summary counts the entries that
688
688
  matched and those that match nothing: delete a stale one.
689
689
 
@@ -4,6 +4,7 @@ require "yaml"
4
4
  require "digest"
5
5
  require "fileutils"
6
6
  require_relative "context_providers"
7
+ require_relative "pages"
7
8
  require_relative "version"
8
9
 
9
10
  module Samagotchi
@@ -50,6 +51,9 @@ module Samagotchi
50
51
  # block_renderers: # optional — a fence's language → the scripts/
51
52
  # - lang: mermaid # files chi web's page loads to draw it
52
53
  # load: [lib.js, draw.js] # (BlockRenderers); each one a scripts: key
54
+ # pages: [schedules.rb] # optional — page scripts (docs/pages.md), each a
55
+ # # scripts: key named NAME.rb: the page NAME
56
+ # # (Pages::Bundled)
53
57
  # session_settings: [cap] # optional — the settings a session may set
54
58
  # # (chi --set cost-cap.cap=3), read by the
55
59
  # # plugin from ctx.settings at call time;
@@ -109,7 +113,7 @@ module Samagotchi
109
113
  # here is one this chi ignores: #unknown_keys, which `chi bundle check`
110
114
  # and the Installer say.
111
115
  KEYS = %w[name version scope description files hooks trust_level plugin requires_chi requires_chi_next needs
112
- scripts context_providers block_renderers includes session_settings settings].freeze
116
+ scripts context_providers block_renderers pages includes session_settings settings].freeze
113
117
 
114
118
  # The first chi release that reads each manifest key or shape (from git:
115
119
  # the first tag whose manifest.rb reads it), for `chi bundle check`'s
@@ -132,13 +136,14 @@ module Samagotchi
132
136
  "settings" => "0.143.0",
133
137
  "block_renderers" => "0.151.0",
134
138
  "plugin.required" => "0.157.0",
135
- "plugin.parts" => "0.183.0"
139
+ "plugin.parts" => "0.183.0",
140
+ "pages" => "0.189.0"
136
141
  }.freeze
137
142
 
138
143
  # files: name → "sha256:<hex>" (both forms); file_descriptions: name →
139
144
  # the description a mapping gave, for the files that have one.
140
145
  attr_reader :name, :version, :scope, :description, :files, :file_descriptions, :trust_level, :plugin, :requires_chi, :needs, :includes,
141
- :scripts, :context_providers, :block_renderers, :session_settings, :session_setting_types, :settings, :setting_types, :unknown_keys
146
+ :scripts, :context_providers, :block_renderers, :pages, :session_settings, :session_setting_types, :settings, :setting_types, :unknown_keys
142
147
 
143
148
  def initialize(path:)
144
149
  @path = path
@@ -169,6 +174,7 @@ module Samagotchi
169
174
  @scripts = parse_scripts(raw["scripts"])
170
175
  @context_providers = parse_context_providers(raw["context_providers"])
171
176
  @block_renderers = parse_block_renderers(raw["block_renderers"])
177
+ @pages = parse_pages(raw["pages"])
172
178
  @includes = parse_includes(raw["includes"])
173
179
  @session_settings = self.class.parse_session_settings(raw["session_settings"])
174
180
  @session_setting_types = self.class.parse_session_setting_types(raw["session_settings"])
@@ -200,7 +206,7 @@ module Samagotchi
200
206
  # that key, which reads as empty with its message in the problems:
201
207
  # name, version (never checked: identity is the record's), scope;
202
208
  # files and their descriptions, scripts, plugin (hooks: is ignored,
203
- # HooksRetired); needs, context_providers; block_renderers
209
+ # HooksRetired); needs, context_providers; block_renderers and pages
204
210
  # (against +fallback_scripts+ when scripts: failed); includes (after
205
211
  # what its check reads); session_settings with its types, settings
206
212
  # with theirs (one raw value each, so one problem); requires_chi,
@@ -304,6 +310,7 @@ module Samagotchi
304
310
  found["scripts"] = SINCE["scripts"] unless @scripts.empty?
305
311
  found["context_providers"] = SINCE["context_providers"] unless @context_providers.empty?
306
312
  found["block_renderers"] = SINCE["block_renderers"] unless @block_renderers.empty?
313
+ found["pages"] = SINCE["pages"] if !@pages.empty? && SINCE.key?("pages")
307
314
  found["plugin.required"] = SINCE["plugin.required"] if @plugin&.dig(:required) && SINCE.key?("plugin.required")
308
315
  found["plugin.parts"] = SINCE["plugin.parts"] if @plugin&.dig(:parts) && SINCE.key?("plugin.parts")
309
316
  found["session_settings"] = SINCE["session_settings"] unless @session_settings.empty?
@@ -318,7 +325,7 @@ module Samagotchi
318
325
  # +file_descriptions+ (name → text) writes those files as mappings.
319
326
  def self.write(dir:, name:, version:, files:, scope: nil, description: "", trust_level: nil,
320
327
  plugin: nil, requires_chi: nil, needs: nil, scripts: {}, context_providers: [], block_renderers: [], file_descriptions: {},
321
- session_settings: [], session_setting_types: {}, settings: nil, setting_types: {})
328
+ session_settings: [], session_setting_types: {}, settings: nil, setting_types: {}, pages: [])
322
329
  FileUtils.mkdir_p(dir)
323
330
  manifest = {
324
331
  "name" => name,
@@ -344,6 +351,7 @@ module Samagotchi
344
351
  manifest["scripts"] = scripts.transform_keys(&:to_s) unless scripts.empty?
345
352
  manifest["context_providers"] = context_providers.map(&:to_h) unless context_providers.empty?
346
353
  manifest["block_renderers"] = block_renderers.map(&:to_h) unless block_renderers.empty?
354
+ manifest["pages"] = pages.map(&:to_s) unless pages.empty?
347
355
  manifest["session_settings"] = session_settings_entry(session_settings, session_setting_types) unless Array(session_settings).empty?
348
356
  manifest["settings"] = session_settings_entry(settings, setting_types) unless settings.nil?
349
357
  File.write(File.join(dir, "manifest.yml"), YAML.dump(manifest))
@@ -452,6 +460,7 @@ module Samagotchi
452
460
  @context_providers = tolerate(problems, "context_providers", []) { parse_context_providers(raw["context_providers"]) }
453
461
  script_names = problems.key?("scripts") ? fallback_scripts.map(&:to_s) : @scripts.keys
454
462
  @block_renderers = tolerate(problems, "block_renderers", []) { parse_block_renderers(raw["block_renderers"], script_names) }
463
+ @pages = tolerate(problems, "pages", []) { parse_pages(raw["pages"], script_names) }
455
464
  @includes = tolerate(problems, "includes", []) { parse_includes(raw["includes"]) }
456
465
  @session_settings, @session_setting_types = tolerate(problems, "session_settings", [[], {}]) do
457
466
  [self.class.parse_session_settings(raw["session_settings"]), self.class.parse_session_setting_types(raw["session_settings"])]
@@ -650,6 +659,26 @@ module Samagotchi
650
659
  raise ValidationError, e.message
651
660
  end
652
661
 
662
+ # pages: → the page scripts in order, each a scripts: key; [] when absent.
663
+ # @param script_names [Array<String>] the scripts: keys
664
+ # @raise [ValidationError]
665
+ def parse_pages(raw, script_names = @scripts.keys)
666
+ return [] if raw.nil?
667
+ raise ValidationError, "pages: must be a list of script names in scripts/ (NAME.rb)" unless raw.is_a?(Array)
668
+
669
+ raw.each do |file|
670
+ unless file.is_a?(String) && file.end_with?(".rb") && Pages.valid_name?(file.delete_suffix(".rb"))
671
+ raise ValidationError, "pages: #{file.inspect} isn't a page script (NAME.rb, NAME lowercase letters, digits " \
672
+ "and hyphens, at most 40)"
673
+ end
674
+ raise ValidationError, "pages: #{file} isn't under scripts:" unless script_names.include?(file)
675
+ end
676
+ twice = raw.tally.select { |_file, count| count > 1 }.keys
677
+ raise ValidationError, "pages: #{twice.join(", ")} listed more than once" unless twice.empty?
678
+
679
+ raw
680
+ end
681
+
653
682
  # includes: → the names in order, duplicates dropped; [] when absent.
654
683
  # A meta ships nothing of its own, so files, hooks or a plugin next
655
684
  # to it is a ValidationError.
@@ -164,6 +164,21 @@ rules:
164
164
  scopes: [once]
165
165
  reason: attaches a command chi will run every few minutes, outside the guardrails
166
166
 
167
+ # ── a schedule's condition: a shell command the tick runs unattended ──
168
+ # chi schedule add|edit --if CMD (and --no-if) is the owner's: the tick
169
+ # runs CMD later, outside the guardrails, and chi schedule refuses the
170
+ # flag inside a session (SAMAGOTCHI_PARENT_SESSION), which an agent can
171
+ # unset. This asks every time, and only the user may allow it (core's
172
+ # PROTECTED_RULES; System 1 never: NEVER_AUTO). The same shapes as
173
+ # chi-context-cmd: quoted words, continuations, --if=…, --remote NAME
174
+ # before the word, and xargs chi schedule add|edit whatever it is fed.
175
+ - id: chi-schedule-if
176
+ tool: shell
177
+ command: '\bchi["'']?(?:[\s\\]+["'']?--remote(?:=|["'']?[\s\\]+["'']?)[^\s"''\\;&|]+["'']?)*[\s\\]+["'']?schedule["'']?[\s\\]+["'']?(?:add|edit)\b(?:[^\n]|\\\n)*[\s"''\\]--(?:no-)?if(?:[\s="''\\]|$)|\bxargs\b[^;&|\n]*\bchi["'']?(?:[\s\\]+["'']?--remote(?:=|["'']?[\s\\]+["'']?)[^\s"''\\;&|]+["'']?)*[\s\\]+["'']?schedule["'']?[\s\\]+["'']?(?:add|edit)\b'
178
+ verdict: ask
179
+ scopes: [once]
180
+ reason: sets a shell command chi's schedule tick runs unattended, outside the guardrails
181
+
167
182
  # ── chi broadcast: for the user, not an agent ─────────────────────────
168
183
  # chi broadcast refuses to run inside a session (SAMAGOTCHI_PARENT_SESSION
169
184
  # is set there), but an agent can unset that; this asks every time, and
@@ -1,8 +1,8 @@
1
1
  ---
2
2
  name: guardrails
3
- version: 0.9.3
3
+ version: 0.9.4
4
4
  scope: system
5
- description: Optional default guardrail rules (git push/rewrites, rm -rf wide, curl | sh, git hooks, chi's own config and attached context from the shell, chi context add --cmd, chi broadcast, answering chi around chi answer, removing a memory, writing a memory that reaches the system prompt (identity, model notes) or a model overlay; in strict mode also git rebase and writes and git in another checkout outside the session's repo), asks only small models get (git checkout --/restore, git stash drop), and a note for the model
5
+ description: Optional default guardrail rules (git push/rewrites, rm -rf wide, curl | sh, git hooks, chi's own config and attached context from the shell, chi context add --cmd, chi schedule --if, chi broadcast, answering chi around chi answer, removing a memory, writing a memory that reaches the system prompt (identity, model notes) or a model overlay; in strict mode also git rebase and writes and git in another checkout outside the session's repo), asks only small models get (git checkout --/restore, git stash drop), and a note for the model
6
6
  trust_level: reviewed
7
7
  # models: in small-models.yml (guardrails.small_models) needs 0.8.1; git: in rules.yml needs 0.17.0;
8
8
  # a rule's memory: key (memory-remove) needs 0.36.0, and its overlay and prompt values (model-overlay-write,
@@ -0,0 +1,11 @@
1
+ ---
2
+ name: schedules
3
+ version: 0.1.1
4
+ scope: system
5
+ description: "A Schedules page in chi web (#/p/schedules, chi page run schedules): every durable schedule, why one is off and how to turn it on, and the recent runs; read-only"
6
+ trust_level: reviewed
7
+ # runtime.schedules' condition (the If column) is new in the next chi (release:bump sets the floor)
8
+ requires_chi: ">= 0.190.0"
9
+ scripts:
10
+ schedules.rb: sha256:ac1bf79cb3df54511c0263cd7dde7e671f853a66c932606c8e2a235835afb44d
11
+ pages: [schedules.rb]