samagotchi 0.178.0 → 0.179.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +28 -1
  3. data/docs/architecture.md +4 -2
  4. data/docs/bundles.md +16 -7
  5. data/docs/cli.md +3 -1
  6. data/docs/context.md +25 -1
  7. data/docs/guardrails.md +2 -1
  8. data/docs/internals/attached-context.md +26 -4
  9. data/docs/internals/background-tasks.md +3 -0
  10. data/docs/internals/block-renderers.md +2 -2
  11. data/docs/internals/bridge.md +11 -2
  12. data/docs/internals/bundles.md +63 -34
  13. data/docs/internals/engine.md +1 -1
  14. data/docs/internals/web-frontend.md +18 -1
  15. data/docs/plugins.md +14 -3
  16. data/docs/releasing.md +3 -3
  17. data/docs/scheduling.md +4 -0
  18. data/docs/sessions.md +8 -2
  19. data/docs/testing.md +4 -1
  20. data/lib/samagotchi/block_renderers.rb +12 -14
  21. data/lib/samagotchi/bootstrap/bundles.rb +2 -2
  22. data/lib/samagotchi/bootstrap_command.rb +1 -1
  23. data/lib/samagotchi/bridge/card_wait.rb +34 -0
  24. data/lib/samagotchi/bridge/turn_accumulator.rb +22 -4
  25. data/lib/samagotchi/bundle_command/check.rb +10 -10
  26. data/lib/samagotchi/bundle_command/installed_check.rb +2 -2
  27. data/lib/samagotchi/bundle_command/try/sandbox.rb +3 -3
  28. data/lib/samagotchi/bundle_command.rb +17 -17
  29. data/lib/samagotchi/bundle_manifest.rb +579 -0
  30. data/lib/samagotchi/bundle_needs.rb +9 -8
  31. data/lib/samagotchi/bundle_settings_check.rb +9 -8
  32. data/lib/samagotchi/bundles/claude-peer/manifest.yml +5 -3
  33. data/lib/samagotchi/bundles/claude-peer/plugin.rb +4 -4
  34. data/lib/samagotchi/bundles/claude-peer/scripts/chi-peer-SKILL.md +11 -6
  35. data/lib/samagotchi/bundles/codex-peer/manifest.yml +5 -3
  36. data/lib/samagotchi/bundles/codex-peer/plugin.rb +4 -3
  37. data/lib/samagotchi/bundles/codex-peer/scripts/chi-peer-SKILL.md +11 -6
  38. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  39. data/lib/samagotchi/bundles/system/memory_guide.md +1 -1
  40. data/lib/samagotchi/config.rb +2 -2
  41. data/lib/samagotchi/context_absorber.rb +36 -6
  42. data/lib/samagotchi/context_note.rb +8 -5
  43. data/lib/samagotchi/context_providers.rb +30 -27
  44. data/lib/samagotchi/context_sources.rb +42 -12
  45. data/lib/samagotchi/engine/messages.rb +1 -1
  46. data/lib/samagotchi/events.rb +6 -5
  47. data/lib/samagotchi/guardrail_wiring.rb +20 -21
  48. data/lib/samagotchi/guardrails/approval.rb +3 -2
  49. data/lib/samagotchi/guardrails/outside.rb +3 -3
  50. data/lib/samagotchi/{memory_bundle → installed_bundles}/bundle_hook.rb +1 -1
  51. data/lib/samagotchi/installed_bundles/dir.rb +129 -0
  52. data/lib/samagotchi/{memory_bundle → installed_bundles}/file_digest.rb +1 -1
  53. data/lib/samagotchi/{memory_bundle → installed_bundles}/file_standing.rb +2 -2
  54. data/lib/samagotchi/{memory_bundle/installed_manifest.rb → installed_bundles/manifest.rb} +21 -21
  55. data/lib/samagotchi/{memory_bundle → installed_bundles}/plugin_ref.rb +2 -2
  56. data/lib/samagotchi/{memory_bundle/installed_bundle.rb → installed_bundles/record.rb} +17 -17
  57. data/lib/samagotchi/installed_bundles/sha.rb +41 -0
  58. data/lib/samagotchi/installed_bundles/standing.rb +45 -0
  59. data/lib/samagotchi/installed_bundles.rb +90 -0
  60. data/lib/samagotchi/memory_bundle/asset_installer.rb +7 -7
  61. data/lib/samagotchi/memory_bundle/builder.rb +13 -13
  62. data/lib/samagotchi/memory_bundle/file_state.rb +9 -9
  63. data/lib/samagotchi/memory_bundle/installed_copy.rb +6 -6
  64. data/lib/samagotchi/memory_bundle/installer.rb +33 -33
  65. data/lib/samagotchi/memory_bundle/listing.rb +5 -5
  66. data/lib/samagotchi/memory_bundle/manifest_standing.rb +7 -7
  67. data/lib/samagotchi/memory_bundle/merger.rb +15 -15
  68. data/lib/samagotchi/memory_bundle/profile.rb +8 -8
  69. data/lib/samagotchi/memory_bundle/provenance.rb +59 -192
  70. data/lib/samagotchi/memory_bundle/remerge.rb +16 -16
  71. data/lib/samagotchi/memory_bundle/shas.rb +2 -2
  72. data/lib/samagotchi/memory_bundle/shipped_history.rb +1 -1
  73. data/lib/samagotchi/memory_bundle/shipped_update.rb +17 -17
  74. data/lib/samagotchi/memory_bundle/status.rb +15 -15
  75. data/lib/samagotchi/memory_bundle/system_bundle.rb +12 -12
  76. data/lib/samagotchi/memory_bundle/trash.rb +2 -2
  77. data/lib/samagotchi/memory_bundle/uninstaller.rb +8 -8
  78. data/lib/samagotchi/memory_bundle.rb +2 -2
  79. data/lib/samagotchi/memory_command.rb +4 -4
  80. data/lib/samagotchi/{memory_bundle → memory_index}/entry_size.rb +8 -8
  81. data/lib/samagotchi/{memory_bundle/index_size.rb → memory_index/size.rb} +6 -6
  82. data/lib/samagotchi/{memory_bundle/index_sync.rb → memory_index/sync.rb} +5 -5
  83. data/lib/samagotchi/{memory_bundle/index_updater.rb → memory_index/updater.rb} +2 -2
  84. data/lib/samagotchi/memory_usage.rb +5 -5
  85. data/lib/samagotchi/muted_memories.rb +1 -1
  86. data/lib/samagotchi/peer_exchanges.rb +76 -0
  87. data/lib/samagotchi/plugin/context.rb +4 -0
  88. data/lib/samagotchi/plugin/loader.rb +35 -33
  89. data/lib/samagotchi/plugin/peer.rb +42 -11
  90. data/lib/samagotchi/project_subfolders.rb +9 -9
  91. data/lib/samagotchi/reply_wait/target.rb +11 -4
  92. data/lib/samagotchi/self_report.rb +14 -14
  93. data/lib/samagotchi/session_access/local.rb +16 -1
  94. data/lib/samagotchi/session_access/remote.rb +2 -1
  95. data/lib/samagotchi/session_config.rb +23 -19
  96. data/lib/samagotchi/session_manager/running_tasks.rb +15 -2
  97. data/lib/samagotchi/session_retention.rb +13 -4
  98. data/lib/samagotchi/session_stores.rb +3 -0
  99. data/lib/samagotchi/system_prompt.rb +4 -4
  100. data/lib/samagotchi/terminal_ui/attach_launcher.rb +5 -1
  101. data/lib/samagotchi/terminal_ui/formatting.rb +2 -2
  102. data/lib/samagotchi/terminal_ui/model_segments_text.rb +5 -5
  103. data/lib/samagotchi/terminal_ui.rb +4 -1
  104. data/lib/samagotchi/testing/bundle.rb +3 -3
  105. data/lib/samagotchi/testing/install.rb +3 -3
  106. data/lib/samagotchi/testing/sandbox.rb +2 -2
  107. data/lib/samagotchi/tool_runner.rb +14 -14
  108. data/lib/samagotchi/tools/memory.rb +22 -22
  109. data/lib/samagotchi/update_command.rb +4 -4
  110. data/lib/samagotchi/version.rb +1 -1
  111. data/lib/samagotchi/web/app.rb +14 -1
  112. data/lib/samagotchi/web/message_display.rb +6 -0
  113. data/lib/samagotchi/web/participant_view.rb +1 -1
  114. data/lib/samagotchi/web/proxy_gate.rb +1 -0
  115. data/lib/samagotchi/web/public/card_kinds.js +8 -3
  116. data/lib/samagotchi/web/public/cards_place.js +15 -1
  117. data/lib/samagotchi/web/public/ctx.js +1 -1
  118. data/lib/samagotchi/web/public/history_shape.js +3 -0
  119. data/lib/samagotchi/web/public/turn_block.js +46 -8
  120. data/lib/samagotchi/web/public/turn_settle.js +117 -0
  121. data/lib/samagotchi/web/push/notifier.rb +2 -2
  122. data/lib/samagotchi/web/session_access_routes.rb +21 -1
  123. data/lib/samagotchi/web/session_hub.rb +20 -4
  124. data/lib/samagotchi/worker_boot.rb +4 -1
  125. metadata +19 -12
  126. data/lib/samagotchi/memory_bundle/manifest.rb +0 -581
@@ -3,7 +3,16 @@
3
3
  How `lib/samagotchi/memory_bundle/` turns a bundle (a dir, git URL, zip or tar holding `manifest.yml`, `*.md`
4
4
  memories and optional `guardrails/`, a plugin file and `scripts/`) into installed state, and back. The
5
5
  user-facing side (what a bundle owns, profiles, needs) is in [memory.md](../memory.md#what-a-bundle-owns) and
6
- [plugins.md](../plugins.md) and [bundles.md](../bundles.md).
6
+ [plugins.md](../plugins.md) and [bundles.md](../bundles.md). The managed memory index helpers live in
7
+ `lib/samagotchi/memory_index/`.
8
+
9
+ Three namespaces share the work. `BundleManifest` (`lib/samagotchi/bundle_manifest.rb`) is the `manifest.yml`
10
+ format. `InstalledBundles` (`lib/samagotchi/installed_bundles.rb` + `installed_bundles/`) is the read side of what is
11
+ installed: the records, their manifests, the walk, one bundle's folder and the shas its files are checked against;
12
+ the runtime (the plugin loader, guardrails, context providers, block renderers, session settings) reads bundles only
13
+ through it, and loading it loads nothing of `memory_bundle/` (`spec/samagotchi/installed_bundles_spec.rb`).
14
+ `MemoryBundle` is the install machinery (install, upgrade, merge, build, uninstall, status, listing), built on the
15
+ read side, never the reverse.
7
16
 
8
17
  ## Where things live
9
18
 
@@ -12,7 +21,7 @@ user-facing side (what a bundle owns, profiles, needs) is in [memory.md](../memo
12
21
  project <system>/projects/<project key>
13
22
  *.md, index.md the bundle's memories, one managed index line each ("· from <bundle>")
14
23
  <system memories>/.bundles/ MemoryPaths.bundles_dir
15
- <name>/manifest.json the install record (Provenance#write, read as InstalledBundle)
24
+ <name>/manifest.json the install record (Provenance#write, read as InstalledBundles::Record)
16
25
  <name>/manifest.yml the bundle's own manifest as installed (Provenance#write's manifest_from:), its sha
17
26
  the record's manifest_sha; a dev install links it to the source (DEV_SHA)
18
27
  <name>/bases/ each file's base for the next upgrade's 3-way merge: as installed, or the
@@ -31,71 +40,91 @@ user-facing side (what a bundle owns, profiles, needs) is in [memory.md](../memo
31
40
 
32
41
  | Piece | Role |
33
42
  |---|---|
34
- | `BundleCommand` (`lib/samagotchi/bundle_command.rb`) | `chi bundle install/upgrade/uninstall/status/diff/list/build/trash/new/test/check/try` (`install --dev`: the Installer's `dev:`, links and `Provenance::DEV_SHA`); runs the Installer, prints its summary, runs the conflict agent step; refuses a source already installed under another name (`installed_under_another_name?`: a git URL bundle recorded under its repo's name before the manifest named it). `upgrade` resolves its argument by `upgrade_source`: a git URL or an existing path, then a shipped name, then the bare name of an installed bundle — whose record's source it then uses (a git URL with its `#ref`, a dir or an archive that is still there), printed as `Upgrading NAME from SOURCE`; a dev record is refused with `Installer.dev_install_line`, a recorded source that is relative, empty or gone says so and asks for the path or URL of a copy (`Installer.source_gone_line`, the words `ManifestStanding` uses too). After an upgrade or uninstall that changed the bundle's plugin (or brought one in), one line names the sessions still running its old code (`LiveVersions.workers`, the ones whose worker takes a restart) and `chi sessions restart ID` for each: only the plugin stays in memory, since a bundle's rules reload by their stamp and its scripts run from the replaced files. |
43
+ | `InstalledBundles` (`installed_bundles.rb`) | `.each(holding:, dir:)` (each installed bundle by name, its `Record`; one whose `manifest.json` doesn't read with `error` set, and with `holding:` only those with that key, or that dir when it doesn't read), `.claimants` (which bundles own a memory file), `.dir` (`MemoryPaths.bundles_dir`) |
44
+ | `InstalledBundles::Dir` (installed_bundles/dir.rb) | one bundle's `.bundles/<name>/` as the runtime reads it: `Dir.new(name:, dir:)`, `#record`, `#plugin_dir`, `#plugin_path`, `#scripts_dir`, `#guardrails_dir`, `#kept_manifest_path`, `#file_refusal(kind, file, recorded)` (the one "is this installed file as installed" check: `:plugin`, `:scripts`, `:guardrails`, each with its own order and words today, a `Refusal`). Its only state is the name and the folder; `Provenance` is one |
45
+ | `InstalledBundles::Standing`, `Refusal` (installed_bundles/standing.rb) | the usability verdict: `.standings(holding:, dir:)` (the walk, each bundle's `Standing`), `.standing(name, dir:)` (one record; a `manifest.json` that doesn't parse raises), `Standing.of(name, record)`: `#refusal` is `:unreadable` (the record) or `:too_new` (requires_chi), nil when chi may use it; none of the bundle's own files is hashed (a manifest cache miss hashes the kept `manifest.yml`, as `Manifest.of` does). A `Refusal` has `kind`, `text` and, for `:file_changed`, the `actual` and `expected` shas. Each reader keeps only its reaction (below) |
46
+ | `InstalledBundles::Sha` (installed_bundles/sha.rb) | the record's shas: `.recorded` (either format, `""` for none), `.of_file`, `DEV` (a dev install's `sha256:dev`), `.unchecked?`, `.matches?` |
47
+ | `BundleCommand` (`lib/samagotchi/bundle_command.rb`) | `chi bundle install/upgrade/uninstall/status/diff/list/build/trash/new/test/check/try` (`install --dev`: the Installer's `dev:`, links and `InstalledBundles::Sha::DEV`); runs the Installer, prints its summary, runs the conflict agent step; refuses a source already installed under another name (`installed_under_another_name?`: a git URL bundle recorded under its repo's name before the manifest named it). `upgrade` resolves its argument by `upgrade_source`: a git URL or an existing path, then a shipped name, then the bare name of an installed bundle — whose record's source it then uses (a git URL with its `#ref`, a dir or an archive that is still there), printed as `Upgrading NAME from SOURCE`; a dev record is refused with `Installer.dev_install_line`, a recorded source that is relative, empty or gone says so and asks for the path or URL of a copy (`Installer.source_gone_line`, the words `ManifestStanding` uses too). After an upgrade or uninstall that changed the bundle's plugin (or brought one in), one line names the sessions still running its old code (`LiveVersions.workers`, the ones whose worker takes a restart) and `chi sessions restart ID` for each: only the plugin stays in memory, since a bundle's rules reload by their stamp and its scripts run from the replaced files. |
35
48
  | `BundleCommand::Check` (bundle_command/check.rb) | `chi bundle check [PATH] [--fix] [--set K=V]`: a bundle being written, checked as an install takes it (docs/cli.md lists the codes); parses the manifest from `Shas.parseable` (a placeholder sha is a `sha` finding, not a YAML error), reads the user's installed bundles only for `clash`, and installs and loads through `Testing::Install` in a `Testing::Sandbox` with `force: true`, the log's echoes swallowed |
36
49
  | `BundleCommand::Try` (`bundle_command/try/`) | `chi bundle try PATH -p TEXT`: `Command` (its flags, help and checks) drives the rest and `Render` prints the trace; a filtered-config `Sandbox` (its folders a `SandboxLayout`, the layout `Testing::Sandbox` uses too) installs the tried bundle and shipped `guardrails` / `cost-cap` in a separate child, then `Run` starts one non-interactive chi process from its realpath work dir; `TraceReader` reads that session's analytics, cards (`Bridge::CardStore.saved`, as the web does) and session JSON by id (never `Session.list`), joining timing and tool args for text or experimental JSON output (a turn a `--timeout` interrupt cut keeps its calls like a Ctrl-C, the one cut short answered as interrupted, so its rows come from the saved calls too; `Run::Result#timed_out` becomes `timed_out`). `Sandbox#child_env` is a Hash, never an ENV mutation; it keeps ordinary user model settings and Keychain access while dropping the spawner's session/guardrail/worker markers (`ChildEnv`, the scrub a session's worker spawn uses too). Every dropped key is sent as nil, so the child really lacks it: a spawn env is merged onto the spawner's, so a key only deleted from the Hash is still inherited (`ChildEnv.spawn_env`). The child runs in its own process group: a `--timeout` sends it INT, then `ProcessGroup.stop` (the groups its processes started too); after any exit the group is signalled only while a straggler is still in it, never a reaped group. `Sandbox#stop_leftovers` (before the trace, and in `cleanup`) stops what left the child's tree, found by the sandbox's own records: a delegate's worker by its session's `owner.lock`, a task by its running `task.json` whose pid still leads its group. |
37
50
  | `BundleCommand::ApiCalls` (bundle_command/api_calls.rb) | what a plugin's source calls of the API, by Prism: `#findings` (a call or keyword the API's classes lack, `check`'s `api`), `#keywords` (the floor check's `call(keyword:)`). Its only list is `MEMBERS`, which object a member gives (`ctx.sessions` → `Plugin::Sessions`); a new such object joins it |
38
51
  | `BundleCommand::Scaffold` (bundle_command/scaffold.rb) | `chi bundle new NAME`: the starting files (block-form `plugin:` entry, `requires_chi` at this chi, a kit test that passes as written); the manifest's shas are filled through `Shas.refresh` |
39
52
  | `BundleCommand::TestRun` (bundle_command/test_run.rb) | `chi bundle test`: `RbConfig.ruby -I <chi's lib>` on `test/**/*_test.rb` (Minitest) or `spec/` (RSpec, as `rake bundles:specs`), under `Bundler.with_unbundled_env` when Bundler's runtime is loaded |
40
53
  | `Shas` (shas.rb) | a manifest's `sha256:` lines: `.refresh(dir[, text])` rewrites them line by line (the layout kept; a `files:` entry it can't place raises `Shas::Error`), `.stale` → `[Stale(file, old, new)]` (`old` `""` for a placeholder, nil for a plugin / script entry with no sha line), `.parseable` (a placeholder `sha256: sha256:` isn't YAML). Plain Ruby: `rake bundles:sha` / `bundles:check` (`script/release/release_tools.rb`) and `chi bundle check --fix` share it |
41
- | `FileDigest` (file_digest.rb) | the one digest of a file on disk: `.hex(path)` (its bytes, streamed; nil when the path isn't a file, a raise for one that can't be read), `.sha256(path)` = `"sha256:<hex>"`, nil with no file — the shape a record writes for a rule, plugin or script. `Provenance.file_sha`, `Merger.digest`, `Status.checksum`, `InstalledBundle#source_sha`, `FileStanding.differs?` and the Installer's checksum verifiers all go through it; a digest of bytes already in memory (a merge's text, a memory's content that is also its base) stays with the code holding them |
54
+ | `InstalledBundles::FileDigest` (installed_bundles/file_digest.rb) | the one digest of a file on disk: `.hex(path)` (its bytes, streamed; nil when the path isn't a file, a raise for one that can't be read), `.sha256(path)` = `"sha256:<hex>"`, nil with no file — the shape a record writes for a rule, plugin or script. `InstalledBundles::Sha.of_file`, `Merger.digest`, `Status.checksum`, `InstalledBundles::Record#source_sha`, `FileStanding.differs?` and the Installer's checksum verifiers all go through it; a digest of bytes already in memory (a merge's text, a memory's content that is also its base) stays with the code holding them |
42
55
  | `SourceNormalizer` (source.rb) | source → local dir; a git/zip/tar extract is *owned* and removed after the install |
43
56
  | `SourceIdentity` (source.rb) | what a source is, for comparing two installs of one name: `shipped:<dir>` (any gem or checkout), `git:<url>` (no `#ref`, trailing `/` or `.git`), `path:<realpath>`; nil when it can't place one |
44
57
  | `PreparedSource` (source.rb) | one source normalized once (dir, owned, git commit): `BundleCommand` reads the bundle's name from its `manifest.yml` (the name for every kind of source, a git URL too) and hands it to the Installer (`prepared:`), so a source is cloned or extracted once per command |
45
58
  | `MemoryFiles` | which top-level `*.md` files of a bundle are its memories (`.select`: the `files:` list, else all but README/LICENSE and the like), `.unshipped` (listed, not shipped) and `.symlinks` (skipped: a symlink is never a memory) |
46
- | `Manifest` | parses/validates `manifest.yml` (`name:` is the bundle's name and a directory under `.bundles/`, so a path such as `../x`, `a/b`, `.` or `..` is refused: `name: … is not a bundle name`; YAML that doesn't parse or isn't a mapping is a `ValidationError` too; files, plugin, scripts, needs, requires_chi, includes, context_providers, session_settings: the keys a session's `chi --set` may give, a list or a mapping of them to types (`SESSION_SETTING_TYPES`), recorded at install in `manifest.json` (`session_settings`, `session_setting_types`) for `SessionConfig` to check; settings: the keys config.yml's `bundles: <name>:` may have, the same shape, recorded as `settings` (nil when the manifest has none) and `setting_types` for `BundleSettingsCheck`, whose warnings the Engine holds for the first turn and `SessionConfig`'s refusals share the words of) and writes it (`Manifest.write`, for Builder). It ignores `requires_chi_next`, a shipped bundle's release-time marker (`script/release/release_tools.rb`, docs/releasing.md). `KEYS` is every top-level key it reads, so a key outside it is one this chi ignores: `#unknown_keys`, in the order the manifest lists them, said in `Manifest.unknown_key_line`'s words by the Installer and `chi bundle check`. `SINCE` is the first release that read each key or shape (taken from the tags), and `#floor_keys` names the ones this manifest uses — including the shapes only a newer chi reads (a `files:` mapping, a typed `session_settings:`/`settings:`) — for check's `requires-chi-floor`. A `hooks:` entry is `Manifest::HooksRetired` (a `ValidationError`; `WORDS` is the one wording of the retirement, `.for_key`, `.for_files`, `.files_in` a source's `hooks/*.rb`) on a strict read and ignored by `Manifest.tolerant` |
59
+ | `BundleManifest` (`lib/samagotchi/bundle_manifest.rb`) | parses/validates `manifest.yml` (`name:` is the bundle's name and a directory under `.bundles/`, so a path such as `../x`, `a/b`, `.` or `..` is refused: `name: … is not a bundle name`; YAML that doesn't parse or isn't a mapping is a `ValidationError` too; files, plugin, scripts, needs, requires_chi, includes, context_providers, session_settings: the keys a session's `chi --set` may give, a list or a mapping of them to types (`SESSION_SETTING_TYPES`), recorded at install in `manifest.json` (`session_settings`, `session_setting_types`) for `SessionConfig` to check; settings: the keys config.yml's `bundles: <name>:` may have, the same shape, recorded as `settings` (nil when the manifest has none) and `setting_types` for `BundleSettingsCheck`, whose warnings the Engine holds for the first turn and `SessionConfig`'s refusals share the words of) and writes it (`BundleManifest.write`, for Builder). It ignores `requires_chi_next`, a shipped bundle's release-time marker (`script/release/release_tools.rb`, docs/releasing.md). `KEYS` is every top-level key it reads, so a key outside it is one this chi ignores: `#unknown_keys`, in the order the manifest lists them, said in `BundleManifest.unknown_key_line`'s words by the Installer and `chi bundle check`. `SINCE` is the first release that read each key or shape (taken from the tags), and `#floor_keys` names the ones this manifest uses — including the shapes only a newer chi reads (a `files:` mapping, a typed `session_settings:`/`settings:`) — for check's `requires-chi-floor`. A `hooks:` entry is `BundleManifest::HooksRetired` (a `ValidationError`; `WORDS` is the one wording of the retirement, `.for_key`, `.for_files`, `.files_in` a source's `hooks/*.rb`) on a strict read and ignored by `BundleManifest.tolerant` |
47
60
  | `Installer` | one install/upgrade/dry run of one bundle (below) |
48
61
  | `AssetInstaller` | the parts that live in `.bundles/<name>/`: guardrail rules, plugin, scripts (and `#retire_hooks`: an older chi's `hooks/` removed, below); returns `AssetInstaller::Installed` (the paths the record keeps). Each folder is one loop, `#install_set(kind_of_file, incoming)`: every file's `AssetState` (`AssetState.in`: the files there at any depth, the incoming and the recorded ones), its row in `FileActions`' `ASSET_INSTALL` or (an upgrade over a record) `ASSET_UPGRADE`, one `Installer::FileResult` per incoming file with the state and action (a dry run's word through `AssetInstaller::DRY_WORDS`, nothing written), a `save_first` file copied to the Installer's `Trash` first (`Trash#copy`, as `guardrails/x`, `plugin/x`, `scripts/sub/x`), then the folder replaced; the named-but-missing and symlink `InstallError`s come before it, the checksum warning after the write (a plugin or script, not a dev link). An older chi's `hooks/` keep `Trash#copy_edits` |
49
- | `FileState` (file_state.rb) | one bundle memory as a command meets it, derived, never stored: `FileState.of(key, record:, provenance:, target_dir:, source_dir:, claimants:, shipped:)` reads the file (D), its base (B), the bundle's text (I) and the record's entry (R) once into `Digests` (`disk`, `base`, `incoming`, `recorded`, `marked_incoming`; `:unreadable` for a file it can't read) and names its `kind` and `mark` (`:none`, `:current`, `:legacy` = `InstalledBundle.legacy_mark?`). With a source (install, upgrade, remerge, restore, a plan): `:new`, `:user_same`, `:user_file` (not the bundle's), `:missing`, `:level` (D == I), `:pristine`, `:edited`, `:diverged`, `:pristine_no_base`, `:edited_no_base`, `:dropped_pristine`, `:dropped_edited`, `:dropped_missing` (`shipped: false`: the bundle no longer ships the key), `:unreadable`; with `source_dir: nil` (status, uninstall, diff) only `:pristine`, `:edited`, `:pristine_no_base`, `:edited_no_base`, `:missing`, `:unreadable`. Edited or not is always `#edited?` = `!Provenance.unchanged?` (the one edited rule: the checksum first, then the base); the base then says what changed, and a base the checksum contradicts (equal to an edited file) is no base to merge from (`:edited_no_base`). `#source_moved?` (a mark that speaks of other text than the bundle ships: Remerge's first question), `#shared_with` (the other bundles listing it, `Provenance.claimants` asked lazily, at most once: only a dropped file and an uninstall ask) |
62
+ | `FileState` (file_state.rb) | one bundle memory as a command meets it, derived, never stored: `FileState.of(key, record:, provenance:, target_dir:, source_dir:, claimants:, shipped:)` reads the file (D), its base (B), the bundle's text (I) and the record's entry (R) once into `Digests` (`disk`, `base`, `incoming`, `recorded`, `marked_incoming`; `:unreadable` for a file it can't read) and names its `kind` and `mark` (`:none`, `:current`, `:legacy` = `InstalledBundles::Record.legacy_mark?`). With a source (install, upgrade, remerge, restore, a plan): `:new`, `:user_same`, `:user_file` (not the bundle's), `:missing`, `:level` (D == I), `:pristine`, `:edited`, `:diverged`, `:pristine_no_base`, `:edited_no_base`, `:dropped_pristine`, `:dropped_edited`, `:dropped_missing` (`shipped: false`: the bundle no longer ships the key), `:unreadable`; with `source_dir: nil` (status, uninstall, diff) only `:pristine`, `:edited`, `:pristine_no_base`, `:edited_no_base`, `:missing`, `:unreadable`. Edited or not is always `#edited?` = `!Provenance.unchanged?` (the one edited rule: the checksum first, then the base); the base then says what changed, and a base the checksum contradicts (equal to an edited file) is no base to merge from (`:edited_no_base`). `#source_moved?` (a mark that speaks of other text than the bundle ships: Remerge's first question), `#shared_with` (the other bundles listing it, `InstalledBundles.claimants` asked lazily, at most once: only a dropped file and an uninstall ask) |
50
63
  | `AssetState` (asset_state.rb) | one rule, plugin or script of a bundle's own folder as a command meets it, derived, never stored: `AssetState.of(path, kind_of_file:, recorded:, incoming:)` → `state` (`:new`, `:unchanged` (the source's bytes, a dev link to them too), `:pristine`, `:edited`, `:linked` (a link to other bytes), `:dropped_pristine`, `:dropped_edited`, `:missing`; with no source, as uninstall and status read it, a file there is a `dropped_*` or `:linked`), `#edited?` (the asset rule: `Trash.edit?`, its bytes neither the recorded sha, none recorded counting as edited, nor the incoming file's; a link never), `#label` (`guardrails/x`, as the trash and the plan name it). `AssetState.in(dir, …)` is a folder's set. Read by `AssetInstaller`, `ShippedUpdate#trash_bound`, `Uninstaller#save_edits`, `Status.asset_states` and `chi bundle diff`; `asset_state_spec` checks it against the corpus's asset cases |
51
64
  | `FileActions` (file_actions.rb) | what each command that acts does in each state: one table per command (`INSTALL`, `FORCE` = install and upgrade `--force`, `UPGRADE`, `REMERGE`, `RESTORE`, `UNINSTALL`), a cell keyed `[kind, mark]`, `[kind, :any]` or `[kind, :shared]`, its value an `Action` (`do`: `:write_incoming`, `:merge`, `:decide`, `:keep`, `:skip`, `:move_to_trash`, `:refuse`, `:restore`; `save_first`; `next_base`: `:on_disk`, `:incoming`, `:recorded`, `:none`; `word`, the report bucket; `record`: `:own`, `:keep_entry`, `:mark`, `:hold_mark`, `:clear_mark`, `:drop`, `:not_owned`). `.for(command, state)`. A `:decide` cell (`[:diverged, :any]`, the legacy guard's `[:pristine, :legacy]`) isn't a function of kind and mark: `Merger::Upgrade#decision` answers it with an `Outcome`, which `.decided(outcome, command)` turns into the action. A dry run reads its command's row and doesn't do it (`Installer::DRY_WORDS` gives its word). Assets have their own tables, `ASSET_INSTALL`, `ASSET_UPGRADE` (an upgrade lists a replaced rule as installed, the plugin and a script as updated: the one cell keyed by kind, `[state, kind_of_file]`) and `ASSET_UNINSTALL`, read with `.for_asset(command, asset)`; their `do` adds `:remove` (deleted, `save_first` copying an edit). A new kind or a new acting command adds a row in each table it reaches; `file_actions_spec` checks every cell against the bundle-state corpus |
52
- | `Merger` | the upgrade's merge. `Merger::Upgrade` (provenance, target dir, source dir) is the one way to ask what an upgrade does to a file, nothing written: `#decision(key[, state])` → a `Decision` (the `FileState`, the UPGRADE action with a `:decide` cell answered, and the `Outcome`), `#outcome` its `Outcome` (`status`: `install`, `fast_forward`, `keep`, `noop`, `conflict`, `merged`; `base`: the next base, `Action#next_base`'s words), `#state`, `#forecast` (a `Forecast` of `merged` and `behind` in one pass), `#behind` (a `conflict` outcome as a `FileStanding::Behind`: why, and from `TextMerge.changed_sections` what it missed, nothing for an older mark, whose base may be the user's text), `#paths`, used by the Installer's merge and dry run, `Remerge`, `ShippedUpdate.plan` and `SystemBundle.sync(dry_run:)`. A `:decide` cell runs `.merge_outcome` (`TextMerge` where both sides changed, git once per call: `merged`, with its `TextMerge::Result` and the digest it read as the Outcome's `merge` and `current_sha`; `ALREADY_MERGED`, a `keep` with base `:incoming`, when the merge adds nothing; or `conflict` with that `merge`, whose `why` says why none was possible; no base: `TextMerge::NO_BASE`, a base the checksum contradicts: `FileStanding::LEGACY_BASE`). `.write_merged` puts a merge in place: the digest checked just before the rename (`AtomicFile.write`'s block), through a symlink, the mode kept, the old file in the `Trash`; false when a live `memory_write` got in. A mark from an older chi (`InstalledBundle.legacy_mark?`: no `incoming_sha`, or `legacy_base`, which keeps that known once the digest is recorded, until the mark goes) may have the user's own text as its base, 0.149's doing, and a merge against it would undo that text with nothing to show, or a fast-forward replace all of it: the upgrade's `[:pristine, :legacy]` cell decides: `#decision` makes a fast-forward that takes a line out of the file, and `.merge_outcome` a merge that does, a `conflict` (`FileStanding::LEGACY_BASE`), on the Installer's and `Remerge`'s path alike, unless `ShippedHistory` proves the base is a version chi shipped. The price, with no such gem left or for a bundle chi doesn't ship: a real base looks the same, so such a file whose bundle rewords or removes a line it still holds stays behind until it is resolved by hand, with `--agent` or with `--force`; no retry fixes it. A fast-forward that goes ahead over a mark is a `save_first` cell (`Installer#save_first`): a file put back to its base under this chi's mark, or an older mark with a proved base or an update that only adds. `.markers?` (a file holding a merge's `<<<<<<<`/`>>>>>>>` lines; `=======` alone is a Markdown underline) |
65
+ | `Merger` | the upgrade's merge. `Merger::Upgrade` (provenance, target dir, source dir) is the one way to ask what an upgrade does to a file, nothing written: `#decision(key[, state])` → a `Decision` (the `FileState`, the UPGRADE action with a `:decide` cell answered, and the `Outcome`), `#outcome` its `Outcome` (`status`: `install`, `fast_forward`, `keep`, `noop`, `conflict`, `merged`; `base`: the next base, `Action#next_base`'s words), `#state`, `#forecast` (a `Forecast` of `merged` and `behind` in one pass), `#behind` (a `conflict` outcome as a `FileStanding::Behind`: why, and from `TextMerge.changed_sections` what it missed, nothing for an older mark, whose base may be the user's text), `#paths`, used by the Installer's merge and dry run, `Remerge`, `ShippedUpdate.plan` and `SystemBundle.sync(dry_run:)`. A `:decide` cell runs `.merge_outcome` (`TextMerge` where both sides changed, git once per call: `merged`, with its `TextMerge::Result` and the digest it read as the Outcome's `merge` and `current_sha`; `ALREADY_MERGED`, a `keep` with base `:incoming`, when the merge adds nothing; or `conflict` with that `merge`, whose `why` says why none was possible; no base: `TextMerge::NO_BASE`, a base the checksum contradicts: `FileStanding::LEGACY_BASE`). `.write_merged` puts a merge in place: the digest checked just before the rename (`AtomicFile.write`'s block), through a symlink, the mode kept, the old file in the `Trash`; false when a live `memory_write` got in. A mark from an older chi (`InstalledBundles::Record.legacy_mark?`: no `incoming_sha`, or `legacy_base`, which keeps that known once the digest is recorded, until the mark goes) may have the user's own text as its base, 0.149's doing, and a merge against it would undo that text with nothing to show, or a fast-forward replace all of it: the upgrade's `[:pristine, :legacy]` cell decides: `#decision` makes a fast-forward that takes a line out of the file, and `.merge_outcome` a merge that does, a `conflict` (`FileStanding::LEGACY_BASE`), on the Installer's and `Remerge`'s path alike, unless `ShippedHistory` proves the base is a version chi shipped. The price, with no such gem left or for a bundle chi doesn't ship: a real base looks the same, so such a file whose bundle rewords or removes a line it still holds stays behind until it is resolved by hand, with `--agent` or with `--force`; no retry fixes it. A fast-forward that goes ahead over a mark is a `save_first` cell (`Installer#save_first`): a file put back to its base under this chi's mark, or an older mark with a proved base or an update that only adds. `.markers?` (a file holding a merge's `<<<<<<<`/`>>>>>>>` lines; `=======` alone is a Markdown underline) |
53
66
  | `ShippedHistory` | `.shipped?(bundle, file, path)`: whether those bytes are that file of that bundle (by manifest name, since a shipped dir can be renamed) in an installed `samagotchi-<version>` gem. Reads `<gem dir>/gems/` by hand, for `Gem.path` (set by a chi home's boot string) and the home's `gem_dirs` from home.json (a checkout or another Ruby runs on other gems), never `Gem::Specification`. Size, then bytes, then the manifest. Anything it can't read is no match, which keeps the guard. Asked only when `Merger`'s guard would otherwise fire: with 54 gems on the Studio a miss costs about 4 ms, a hit less |
54
67
  | `TextMerge` | the text merge: `.merge(base:, ours:, theirs:)` → a `Result` (`status` `:clean` with `text`, `:conflict` with `hunks`, `:failed` with `why`). `git merge-file -p --diff3 --marker-size=20` on temp copies in a temp cwd, with every `GIT_*` that points at a repository or a config unset or at `/dev/null` (it can run inside another tool's hook). git isn't a runtime dependency: none on PATH, or macOS's `/usr/bin/git` with no developer tools behind it (`.apple_stub?`, by `xcode-select -p`; running it pops a dialog), is `:failed`. So is a git past `TIMEOUT` (10 s; its process group is killed: this runs under `SystemBundle`'s lock), and any doubt about the answer: `min(hunks, 127)` against the exit status, a status over 127, a NUL in a side, marker lines that don't pair up (a user's line equal to one), a line no input holds, or an empty answer to non-empty inputs. `Scan` reads the output: a hunk unions (ours, then the entries of theirs that ours lacks) only when the last heading before it, at level 1 or 2 and outside code fences, HTML comments and any hunk, is titled exactly `Changelog` or `Change log`, with nothing but list entries (an item and its indented lines) since that heading and no fence or comment open, and base, ours and theirs each hold only list entries, with every base entry still on both sides: both only added. Any other hunk is a real conflict, and markers never leave the module. An entry is an item and the lines indented deeper under it, nested items too, and the union compares whole entries. `.changed_sections(base, theirs, ours)`: the headings of the sections the bundle changed and the file hasn't got, and whether text under no heading did, which is what names a miss: a conflict's hunks can't, since the whole file stays and the one hunk may be a Changelog line beside a whole new section. `Hunk#heading` counts the places under no heading |
55
- | `FileStanding` | the one owner of what chi says of an edited bundle file, used by every surface: `Behind` (`#state`, `#line`: `x.md stays behind 0.8.0: no merge possible (why); missed ## A, ## B, ## C and 2 more`, `would stay` in a dry run), `MergeNote`, `.merged_line`, `.no_merge` (for `LEGACY_BASE` it says chi can't tell whether the file holds edits), `.clauses` (a report's clauses for one bundle), `.behind_count`, `.stay_behind`, `.counts_sentence` (the push), `.still_behind`, `.text` (UTF-8, whatever a name or heading was tagged), `FORCE_TAKES`, `FORCE_MOVES`, `IN_THE_TRASH`. Behind means marked and bytes other than the mark's `incoming_sha` (`.behind?`, read by `InstalledBundle#behind_files` and `Remerge` alike): a file brought level by hand isn't, a missing one is a missing file, and one that can't be read is. An older mark no retry has looked at reads `may be behind` (`Behind#unsure`, and the counts say so), and isn't behind at all when level with its recorded source on disk (`InstalledBundle#behind_file?`). A new surface reads these and adds no wording |
68
+ | `InstalledBundles::FileStanding` (installed_bundles/file_standing.rb) | the one owner of what chi says of an edited bundle file, used by every surface: `Behind` (`#state`, `#line`: `x.md stays behind 0.8.0: no merge possible (why); missed ## A, ## B, ## C and 2 more`, `would stay` in a dry run), `MergeNote`, `.merged_line`, `.no_merge` (for `LEGACY_BASE` it says chi can't tell whether the file holds edits), `.clauses` (a report's clauses for one bundle), `.behind_count`, `.stay_behind`, `.counts_sentence` (the push), `.still_behind`, `.text` (UTF-8, whatever a name or heading was tagged), `FORCE_TAKES`, `FORCE_MOVES`, `IN_THE_TRASH`. Behind means marked and bytes other than the mark's `incoming_sha` (`.behind?`, read by `InstalledBundles::Record#behind_files` and `Remerge` alike): a file brought level by hand isn't, a missing one is a missing file, and one that can't be read is. An older mark no retry has looked at reads `may be behind` (`Behind#unsure`, and the counts say so), and isn't behind at all when level with its recorded source on disk (`InstalledBundles::Record#behind_file?`). A new surface reads these and adds no wording |
56
69
  | `Remerge` | the retry at the same version, memory files only, for a file marked `conflict` (its `FileState` and `REMERGE` row; a `:decide` cell through `Merger::Upgrade#decision`): `#run(dry_run:)` → a `Result` (`merged`, `settled`, `stamped`, `behind`, `warnings`, `trash_copy`). It merges what merges and settles those entries (`Provenance#resolve_conflicts`, the index line refreshed), checking a merged incoming file against the manifest's sha256, in a dry run too. It leaves `version`, `installed_at` and the assets alone: the Installer would `rm_rf` guardrails, plugin and scripts under live sessions. Every file it leaves is in `behind`, with why: one not shipped now (`MemoryFiles.select`) keeps its mark, base and text; one whose `incoming_sha` isn't the shipped text (a checkout at one VERSION) is left alone, no git runs, and it reads as its mark says; a mark with no digest (older chi) is tried as well, and a real conflict then records it (`Provenance#refresh_marks`, which writes only when the mark would read differently, so a conflict at each start writes nothing). A mark whose digest matches is tried on every run, since the file or git may have changed. `noop` and `keep` settle quietly; `fast_forward` waits for the next upgrade, reading as behind until then; `install` is a missing file, which isn't behind, and a warning says so. A file it can't read or replace stays as it is, saying why. Called from `ShippedUpdate.plan_row`/`apply` (`chi update`) and `SystemBundle.sync`'s equal-version branch, under its lock (each chi start and `chi update`); a bundle chi doesn't ship retries through `chi bundle upgrade`. No marks: nothing is read beyond the record. One marked file costs one git run per Engine start, about 12 ms on the Studio (0.1 ms with none) |
57
- | `Provenance` | the `.bundles/<name>/` dir: `#write` the record + bases (its `files:` is the full list: a key left out is dropped, a nil value keeps the entry with no base; `marks:` are the files left behind, each a `FileStanding::Behind`, and `incoming_dir:` the bundle text each speaks of, recorded as `incoming_sha` and saved at `#incoming_path`; an older mark that stays keeps `legacy_base`), `#resolve_conflicts` (base to the incoming file, mark and its fields (`MARK_FIELDS`) and saved text gone; a file whose incoming copy is gone keeps both), `#refresh_marks` (what a retry found: why, missed, the digest and `legacy_base`, the saved text), `#note_merged` and `#clear_merge_notes(notes)` (`MERGE_NOTE_FIELDS`, kept through `#write`; the saved text is best effort, after the manifest, so it can't leave a plugin under the old record's sha; any other failure writing the record still can, until a retry), `#record` → `InstalledBundle`, `.each_installed`, `.claimants` (which bundles own a file). `#write(manifest_from: DIR)` keeps `DIR/manifest.yml` at `#kept_manifest_path` (written aside and renamed; for `dev:` a link to its realpath) and records `manifest_sha` (`FileDigest.sha256`, `DEV_SHA` for dev) and `installed_by` (this chi's VERSION); the Installer and `Profile.install` pass their source dir, and a write without it carries the existing record's two fields, the kept file left alone. The in-place edits (`#resolve_conflicts`, `#record_restored`, `#refresh_marks`, `#note_merged`, `#clear_merge_notes`) keep them. The record's mirror of the manifest keys (`requires_chi` … `setting_types`) is still written from the kwargs, exactly as before: an older chi sharing the memories dir (an old worker, chi web, gem or worktree) reads only the record, and without the mirror's `requires_chi` it would load a too-new bundle's plugin. A key a later manifest gains is never mirrored. Any chi without the kept manifest that rewrites a record drops `manifest_sha` and `installed_by` (it rebuilds the record from its own kwargs). `#adopt_manifest(dir, dry_run:)` heals such a record (`InstalledBundle#manifest_unkept?`: no `manifest_sha`, or its file gone): when `dir` is the source of what's installed (its manifest names the bundle at the recorded version; each mirrored key, normalised as `.mirror_fields` records it (the one shape `#write` uses too), equals the record's, a key the record lacks being fine only when `Manifest::SINCE` has it, since an older chi couldn't have recorded it (a recorded hook doesn't count: retired); and every recorded plugin, hook, script, rule and unmarked memory sha is that of `dir`'s file; else the why names the key or file) it keeps `dir/manifest.yml` and records `manifest_sha`, nothing else (not `installed_at`, the mirror or `installed_by`); otherwise it returns why and writes nothing. Never for a dev record (its next `install --dev` links the file) |
58
- | `InstalledManifest` (installed_manifest.rb) | the one answer to "this installed bundle's manifest" (`InstalledBundle#manifest`): requires_chi, trust_level, needs, the scripts' names, context providers, block renderers, session settings and settings with their types, file descriptions, a profile's includes. Read from the kept `manifest.yml` (`origin: :kept`) when the record's `manifest_sha` is set and the file still has it (`Provenance.sha_matches?`, so a dev link is never checked), else from the record's `mirror` (`origin: :record`), in these cases: no kept file and no `manifest_sha` (a record from before chi kept it; no problem); no kept file, or something other than a file in its place, while `manifest_sha` is set (`:missing`); a kept file and no `manifest_sha` (a chi without the kept manifest rewrote the record: `problems["manifest.yml"] = :stale`); a kept file with another sha, or one that isn't a YAML mapping (`:edited`); the sha matches (`:kept`). `#standing` is that symbol, `#key_problems` the rest. The kept file is read by `Manifest.tolerant` key by key in a fixed order (its comment): a key that doesn't parse under this chi takes the mirror's value if that parses, else empty, with its message in `problems` (a reader that logged it logs that); `block_renderers` is checked against the record's scripts when the kept `scripts:` fails, and an older install's `hooks:` is ignored (no problem row). `description` and `unknown_keys` come only from a kept file; a profile's `includes` is always the record's (its members, identity). The value is deep-frozen, since callers share it. One process-wide cache (a Hash under a Mutex, cleared at `CACHE_LIMIT`) keyed by the record value and the kept file's stat (mtime, size, inode, device; a dev link's target): chi web asks per request, a worker at start and per `ContextProviders.resolve`. `#requires_chi_failure(version = VERSION)` is the one requires_chi gate; `#experimental?`, `#needs?`, `#context_providers?`, `#block_renderers?` |
59
- | `ManifestStanding` (manifest_standing.rb) | the one owner of the words for an installed bundle's `manifest.yml` as `InstalledManifest` read it: `.state` (`:kept`, `:legacy`, `:stale`, `:missing`, `:edited`), `.label` (`[kept]` / `[from the install record]`), `.line(bundle, refused:)` (the case and the command: `chi bundle upgrade NAME` (reads it again from a git URL, or a source that didn't match, with why), `chi update keeps it` while untried, the source is gone (`Installer.source_gone_line`), `chi bundle install --dev SOURCE` for a dev record; for a kept one, only the keys whose `Manifest::SINCE` floor is above the record's `installed_by`: newer than its installer), `.keep(bundle, source_dir:, dry_run:)` → `Outcome` (the record after, the line, `kept`): `Provenance#adopt_manifest` from `source_dir`, else from the recorded source (a dir; a zip/tar through `PreparedSource`, cleaned up; never a git clone). Read by `ShippedUpdate` (`Row#manifest`, the plan's dry `keep` and apply's), `UpdateCommand#external_rows` (a `kept its manifest` row, else a warn row, before the bundle's re-check, which then sees the kept file) and `chi bundle status NAME` (`BundleCommand#manifest_line`: `Manifest:`, the label, `.status_line`: for a record with a folder source (a bundle chi ships: this chi's shipped copy at the recorded version, which `chi update` reads), a dry `adopt_manifest` first, so the line says whether `chi update` keeps it or why not; an archive isn't extracted there, its line says `chi update tries to keep it`; a profile chi doesn't ship is never kept by `chi update`, so its line names `chi bundle upgrade NAME`) |
60
- | `InstalledBundle`, `BundleHook`, `PluginRef` | value objects for the record; tolerant of older records (missing keys read as empty). `InstalledBundle`'s members are identity and state (name, version, scope, source, `installed_at`, `source_commit`, files and their marks, hooks, guardrails, scripts and the plugin with their shas, a profile's `includes`, `dev`, `dir`, the kept manifest's `manifest_sha` and `installed_by`, nil on a record from before it was kept); the manifest keys it records sit in one `mirror` Hash (`MIRROR_KEYS`, frozen: a key a later manifest gains is never mirrored) that only `InstalledManifest` reads, so manifest data is read through `#manifest`. `BundleHook` is an older record's hook entry: `.parse` and `#sha256` (what the retire, uninstall and the trash selection read) |
61
- | `BlockRenderers` (`lib/samagotchi/block_renderers.rb`) | a manifest's `block_renderers:`: `.parse_list`, and what chi web asks without loading plugins: `.for_installed` (first bundle by name wins a language; a record with an error, an unmet `requires_chi` or a list that doesn't parse is skipped) and `.script_path` (`load` membership first, then `Provenance.sha_matches?`). `Manifest` checks each `load` is a `scripts:` key; the files are ordinary scripts everywhere else ([block-renderers.md](block-renderers.md)) |
70
+ | `Provenance` | the `.bundles/<name>/` dir's write side (an `InstalledBundles::Dir`): `#write` the record + bases (its `files:` is the full list: a key left out is dropped, a nil value keeps the entry with no base; `marks:` are the files left behind, each a `FileStanding::Behind`, and `incoming_dir:` the bundle text each speaks of, recorded as `incoming_sha` and saved at `#incoming_path`; an older mark that stays keeps `legacy_base`), `#resolve_conflicts` (base to the incoming file, mark and its fields (`MARK_FIELDS`) and saved text gone; a file whose incoming copy is gone keeps both), `#refresh_marks` (what a retry found: why, missed, the digest and `legacy_base`, the saved text), `#note_merged` and `#clear_merge_notes(notes)` (`MERGE_NOTE_FIELDS`, kept through `#write`; the saved text is best effort, after the manifest, so it can't leave a plugin under the old record's sha; any other failure writing the record still can, until a retry), `#record` → `InstalledBundles::Record` (the Dir's). `#write(manifest_from: DIR)` keeps `DIR/manifest.yml` at `#kept_manifest_path` (written aside and renamed; for `dev:` a link to its realpath) and records `manifest_sha` (`FileDigest.sha256`, `DEV_SHA` for dev) and `installed_by` (this chi's VERSION); the Installer and `Profile.install` pass their source dir, and a write without it carries the existing record's two fields, the kept file left alone. The in-place edits (`#resolve_conflicts`, `#record_restored`, `#refresh_marks`, `#note_merged`, `#clear_merge_notes`) keep them. The record's mirror of the manifest keys (`requires_chi` … `setting_types`) is still written from the kwargs, exactly as before: an older chi sharing the memories dir (an old worker, chi web, gem or worktree) reads only the record, and without the mirror's `requires_chi` it would load a too-new bundle's plugin. A key a later manifest gains is never mirrored. Any chi without the kept manifest that rewrites a record drops `manifest_sha` and `installed_by` (it rebuilds the record from its own kwargs). `#adopt_manifest(dir, dry_run:)` heals such a record (`InstalledBundles::Record#manifest_unkept?`: no `manifest_sha`, or its file gone): when `dir` is the source of what's installed (its manifest names the bundle at the recorded version; each mirrored key, normalised as `#mirror_fields` records it (the one shape `#write` uses too), equals the record's, a key the record lacks being fine only when `BundleManifest::SINCE` has it, since an older chi couldn't have recorded it (a recorded hook doesn't count: retired); and every recorded plugin, hook, script, rule and unmarked memory sha is that of `dir`'s file; else the why names the key or file) it keeps `dir/manifest.yml` and records `manifest_sha`, nothing else (not `installed_at`, the mirror or `installed_by`); otherwise it returns why and writes nothing. Never for a dev record (its next `install --dev` links the file) |
71
+ | `InstalledBundles::Manifest` (installed_bundles/manifest.rb) | the one answer to "this installed bundle's manifest" (`InstalledBundles::Record#manifest`): requires_chi, trust_level, needs, the scripts' names, context providers, block renderers, session settings and settings with their types, file descriptions, a profile's includes. Read from the kept `manifest.yml` (`origin: :kept`) when the record's `manifest_sha` is set and the file still has it (`InstalledBundles::Sha.matches?`, so a dev link is never checked), else from the record's `mirror` (`origin: :record`), in these cases: no kept file and no `manifest_sha` (a record from before chi kept it; no problem); no kept file, or something other than a file in its place, while `manifest_sha` is set (`:missing`); a kept file and no `manifest_sha` (a chi without the kept manifest rewrote the record: `problems["manifest.yml"] = :stale`); a kept file with another sha, or one that isn't a YAML mapping (`:edited`); the sha matches (`:kept`). `#standing` is that symbol, `#key_problems` the rest. The kept file is read by `BundleManifest.tolerant` key by key in a fixed order (its comment): a key that doesn't parse under this chi takes the mirror's value if that parses, else empty, with its message in `problems` (a reader that logged it logs that); `block_renderers` is checked against the record's scripts when the kept `scripts:` fails, and an older install's `hooks:` is ignored (no problem row). `description` and `unknown_keys` come only from a kept file; a profile's `includes` is always the record's (its members, identity). The value is deep-frozen, since callers share it. One process-wide cache (a Hash under a Mutex, cleared at `CACHE_LIMIT`) keyed by the record value and the kept file's stat (mtime, size, inode, device; a dev link's target): chi web asks per request, a worker at start and per `ContextProviders.resolve`. `#requires_chi_failure(version = VERSION)` is the one requires_chi gate; `#experimental?`, `#needs?`, `#context_providers?`, `#block_renderers?` |
72
+ | `ManifestStanding` (manifest_standing.rb) | the one owner of the words for an installed bundle's `manifest.yml` as `InstalledBundles::Manifest` read it: `.state` (`:kept`, `:legacy`, `:stale`, `:missing`, `:edited`), `.label` (`[kept]` / `[from the install record]`), `.line(bundle, refused:)` (the case and the command: `chi bundle upgrade NAME` (reads it again from a git URL, or a source that didn't match, with why), `chi update keeps it` while untried, the source is gone (`Installer.source_gone_line`), `chi bundle install --dev SOURCE` for a dev record; for a kept one, only the keys whose `BundleManifest::SINCE` floor is above the record's `installed_by`: newer than its installer), `.keep(bundle, source_dir:, dry_run:)` → `Outcome` (the record after, the line, `kept`): `Provenance#adopt_manifest` from `source_dir`, else from the recorded source (a dir; a zip/tar through `PreparedSource`, cleaned up; never a git clone). Read by `ShippedUpdate` (`Row#manifest`, the plan's dry `keep` and apply's), `UpdateCommand#external_rows` (a `kept its manifest` row, else a warn row, before the bundle's re-check, which then sees the kept file) and `chi bundle status NAME` (`BundleCommand#manifest_line`: `Manifest:`, the label, `.status_line`: for a record with a folder source (a bundle chi ships: this chi's shipped copy at the recorded version, which `chi update` reads), a dry `adopt_manifest` first, so the line says whether `chi update` keeps it or why not; an archive isn't extracted there, its line says `chi update tries to keep it`; a profile chi doesn't ship is never kept by `chi update`, so its line names `chi bundle upgrade NAME`) |
73
+ | `InstalledBundles::Record`, `BundleHook`, `PluginRef` (installed_bundles/record.rb, bundle_hook.rb, plugin_ref.rb) | value objects for the record; tolerant of older records (missing keys read as empty). `InstalledBundles::Record`'s members are identity and state (name, version, scope, source, `installed_at`, `source_commit`, files and their marks, hooks, guardrails, scripts and the plugin with their shas, a profile's `includes`, `dev`, `dir`, the kept manifest's `manifest_sha` and `installed_by`, nil on a record from before it was kept); the manifest keys it records sit in one `mirror` Hash (`MIRROR_KEYS`, frozen: a key a later manifest gains is never mirrored) that only `InstalledBundles::Manifest` reads, so manifest data is read through `#manifest`. `BundleHook` is an older record's hook entry: `.parse` and `#sha256` (what the retire, uninstall and the trash selection read) |
74
+ | `BlockRenderers` (`lib/samagotchi/block_renderers.rb`) | a manifest's `block_renderers:`: `.parse_list`, and what chi web asks without loading plugins: `.for_installed` (first bundle by name wins a language; a record with an error, an unmet `requires_chi` or a list that doesn't parse is skipped) and `.script_path` (`load` membership first, then `InstalledBundles::Sha.matches?`). `BundleManifest` checks each `load` is a `scripts:` key; the files are ordinary scripts everywhere else ([block-renderers.md](block-renderers.md)) |
62
75
  | `Builder` | `chi bundle build`: memories (+ the installed bundle's rules, plugin, scripts; never an older record's hooks) → zip/tar/dir |
63
76
  | `Profile` | meta bundles (`includes:`): install the members, record which; `InstallResult#kept_own` names a new member's memory files the user already had, with other bytes (`kept_own_line`, printed by `chi bundle`, `chi update` and `chi bootstrap`); a dry run runs each member's Installer as a dry run too, so it names them as well |
64
77
  | `SystemBundle`, `ShippedUpdate` | the built-in system bundle (`ensure!` at Engine start, `sync` in `chi update`) and `chi update`'s upgrade of shipped bundles; both drive the Installer with `upgrade: true` and `Remerge` at an equal version (`ShippedUpdate::Row`'s `:would_merge`, `:merged`; `SystemBundle::Result`'s `:merged`). `SystemBundle` also puts back a memory missing at an equal version, that file alone, with no Installer (`verify_files_present`, `Provenance#record_restored`), checked against the manifest's `files:` sha as an installed one is (`FileDigest.mismatch`). A sync's `Result#warnings` reach `chi update`'s row (`UpdateCommand#system_bundle_row`) and `chi bootstrap`'s line (`BootstrapCommand#system_bundle_line`); `ShippedUpdate.apply` puts an update's `Checksum mismatch` warnings in `Row#note`. `ensure!` echoes a merge in one line, in the row's words. That reaches a terminal launch; a worker has only its log (`Log.configure(stderr: false)`), so every merge leaves a note on the file's record (`Installer#note_merges`, a failed run's too, and `Remerge#note_merges`; `Provenance#note_merged`: version, time, trash dir). `chi bundle status` shows it, and `chi update` reads the notes before the run (`SystemBundle.merge_notes`, `ShippedUpdate::Row#earlier`), names them in the row and clears after it those exact ones and the notes of the files that run merged (a worker's meanwhile, on another file, stays), unless it was a dry run, the row failed or has no place for them (a skipped system row), or the run is unattended (`ChildEnv::UNATTENDED_UPDATE`, which `Web::UpdateOps` sets for `update.auto`, an env marker so a hand-over's exec keeps it and an older chi ignores it; `--json` alone says nothing, as a person or script may use it). `chi bundle upgrade` clears the notes of what it printed, and `--force` those of the files it replaced. `--json`'s `merged` is this run's, `earlier` the notes'. `ensure!` says what an upgrade left behind and nothing of a file already behind, which `Result#behind` still has for the row. A plan or sync that can't read a file is that bundle's failed row, in `Trash.failure_message`'s words (`ShippedUpdate.plan_row`, `SystemBundle.sync`). At an equal version both keep the shipped `manifest.yml` for a record an older chi wrote (`Provenance#adopt_manifest` from the shipped dir): `SystemBundle.sync` under its lock, not in a dry run (so at the first Engine start or `chi update` after the upgrade, once), and `ShippedUpdate.apply` for a row that ends `:up_to_date` or `:merged` (`#keep_manifest`, through `ManifestStanding.keep`: `Row#manifest` is its line, `would keep its manifest` from the plan's dry run, appended to the row's status); a bumped bundle gets it from its Installer. `ShippedUpdate::Row#replaced` is what the upgrade copies to the trash (`ShippedUpdate.trash_bound`: the edited `AssetState`s against the shipped source over the rules, plugin and scripts folders, and `Trash.edits` over an older record's `hooks/` (which `#retire_hooks` removes whole), no recorded sha counting as edited), the same rule and files as `AssetInstaller`'s copies. `ShippedUpdate.edited_executables` (`chi bundle check`'s "does chi load it?") stays sha-only, as `Status.plugin_status` does. `ShippedUpdate.external` is the rest: what `chi update` only checks |
65
- | `InstalledCopy`, `BundleCommand::InstalledCheck` | `chi update`'s re-check of the bundles chi didn't ship ([docs/cli.md](../cli.md#updating)). `InstalledCopy` lays a record and its installed files out as a source folder (manifest.yml from `Manifest.write`, the files' own shas, memories from `bases/`; its `files:`, `plugin:` and `scripts:` are always what the record and the copy hold (no `hooks:`), so a memory the install left out or one with no base gives no `missing-file`, and every other key is the kept `manifest.yml`'s when `InstalledManifest` read it, so the check sees its unknown keys, else the mirror's; a kept key that didn't parse keeps the value `InstalledManifest` fell back to, since `InstalledCheck` already names its problem); `InstalledCheck` forks per bundle (a plugin's `exit` or hang is that bundle's row; stdio to /dev/null, so `--json` stays parseable; `TIMEOUT`, then KILL of its group) and runs `Check.new(dir, installed: true)` there, which leaves out what only suits a source tree. Its `boundary` finding is narrower there than in a source tree: `Testing::Boundary.gone?` calls a reference gone only when its constant doesn't resolve or the object has no method the name names, so a bundle reaching `Samagotchi::Log` gets no row. lib loads lazily, so when a name doesn't resolve `gone?` requires every file of this chi's library in that same child and asks again (about 0.2 s, only for a bundle that reaches into chi at all); anything it can't read — a `const_get`, a require of a file that is there — is taken as still there. The fork is the point: `Sandbox` swaps ENV and the plugin's code is arbitrary. `UpdateCommand#external_rows` makes the rows (`level`, never `failed`) and holds the check back while a newer gem is yet to take over (`@not_checked`), since a fork is this chi's code |
78
+ | `InstalledCopy`, `BundleCommand::InstalledCheck` | `chi update`'s re-check of the bundles chi didn't ship ([docs/cli.md](../cli.md#updating)). `InstalledCopy` lays a record and its installed files out as a source folder (manifest.yml from `BundleManifest.write`, the files' own shas, memories from `bases/`; its `files:`, `plugin:` and `scripts:` are always what the record and the copy hold (no `hooks:`), so a memory the install left out or one with no base gives no `missing-file`, and every other key is the kept `manifest.yml`'s when `InstalledBundles::Manifest` read it, so the check sees its unknown keys, else the mirror's; a kept key that didn't parse keeps the value `InstalledBundles::Manifest` fell back to, since `InstalledCheck` already names its problem); `InstalledCheck` forks per bundle (a plugin's `exit` or hang is that bundle's row; stdio to /dev/null, so `--json` stays parseable; `TIMEOUT`, then KILL of its group) and runs `Check.new(dir, installed: true)` there, which leaves out what only suits a source tree. Its `boundary` finding is narrower there than in a source tree: `Testing::Boundary.gone?` calls a reference gone only when its constant doesn't resolve or the object has no method the name names, so a bundle reaching `Samagotchi::Log` gets no row. lib loads lazily, so when a name doesn't resolve `gone?` requires every file of this chi's library in that same child and asks again (about 0.2 s, only for a bundle that reaches into chi at all); anything it can't read — a `const_get`, a require of a file that is there — is taken as still there. The fork is the point: `Sandbox` swaps ENV and the plugin's code is arbitrary. `UpdateCommand#external_rows` makes the rows (`level`, never `failed`) and holds the check back while a newer gem is yet to take over (`@not_checked`), since a fork is this chi's code |
66
79
  | `Uninstaller`, `Trash`, `Status`, `Listing` | remove (the bundle's own folder too: an edited file there is copied to the trash first, `Uninstaller#trash_copy_line`); keep removed files (`Trash#move`) and a copy of overwritten ones (`Trash#copy`, its `as:` keeping a subfolder); `Provenance.unchanged?` (the record's checksum, else the base; neither counts as edited) is the one edited rule, read by `prune_dropped_files`, the uninstall's refusal and `chi bundle status`'s `modified`; `chi bundle status` (per file, `behind`, `merge_note`, `unreadable`; per rule and script `Status.asset_states`: ok, `modified` = `AssetState#edited?`, missing; `issues=` counts behind, missing and unreadable files, a missing or edited rule (it doesn't load) and a missing script, not an edited memory or script); `chi bundle list` (`Installed#behind`) |
67
- | `IndexUpdater`, `IndexSync` | the managed `index.md` lines (Installer; and the write/edit tools for memories) |
68
- | `EntrySize` | one memory's size in tokens: `memory.entry_warn_tokens`' crossing note after a memory write, `chi self`'s `big memories` row |
69
- | `IndexSize` | one scope's memory index as the prompt carries it (tokens, lines, bytes): `memory.index_warn_tokens`' crossing note after a memory write, `chi self`'s summary, the prompt's figures (`SystemPrompt`) |
80
+ | `MemoryIndex::Updater`, `MemoryIndex::Sync` | the managed `index.md` lines (Installer; and the write/edit tools for memories) |
81
+ | `MemoryIndex::EntrySize` | one memory's size in tokens: `memory.entry_warn_tokens`' crossing note after a memory write, `chi self`'s `big memories` row |
82
+ | `MemoryIndex::Size` | one scope's memory index as the prompt carries it (tokens, lines, bytes): `memory.index_warn_tokens`' crossing note after a memory write, `chi self`'s summary, the prompt's figures (`SystemPrompt`) |
70
83
  | `Placeholder` | `{{placeholder}}` patterns left in an installed memory, one line per file from `Installer#detect_placeholders`; a hint, never a gate |
71
84
 
72
85
  A dev install (`chi bundle install --dev PATH`, `Installer#initialize(dev: true)`) links instead of copying:
73
86
  `AssetInstaller#place` symlinks each rule file, plugin and script into `.bundles/<name>/` to its realpath in
74
87
  the source (memories are still copied: their bases and the index are the install's), and the record gets `"dev": true`
75
- (`InstalledBundle#dev`, `source` the realpath) with `Provenance::DEV_SHA` (`sha256:dev`, never a hex digest) in
76
- place of every rule, plugin and script sha256. `Provenance.sha_matches?` / `.unchecked?` read it as "not
88
+ (`InstalledBundles::Record#dev`, `source` the realpath) with `InstalledBundles::Sha::DEV` (`sha256:dev`, never a hex digest) in
89
+ place of every rule, plugin and script sha256. `InstalledBundles::Sha.matches?` / `.unchecked?` read it as "not
77
90
  checked", which is how the readers below skip it for that bundle only. `Installer#refuse_dev_mismatch` keeps a dev
78
91
  and a normal install from replacing each other (this is also why `chi bundle upgrade` refuses a dev bundle);
79
92
  `Uninstaller` removes links with `rm_rf`/`rm_f`, which never follow them into the source.
80
93
 
81
- Readers of the installed state: `GuardrailWiring#bundle_rules`, `Plugin::Loader`,
82
- `ContextProviders` (scripts), `BundleNeeds` (index markers). Each goes through `Provenance.each_installed` / `#record`
83
- and checks the recorded sha256 (and `requires_chi`) before loading. `ContextProviders.resolve`/`.any?` skip a bundle
84
- whose `requires_chi` this chi doesn't meet, logging `providers_too_new` once per process per bundle and version (a
85
- Set under a Mutex, like `GuardrailWiring`'s kept-rules notice), and `.command_for` raises `Invalid` for a source
86
- attached to one. They read shas and state off the record, and
87
- manifest data (requires_chi, needs, providers, renderers, settings) through `InstalledBundle#manifest`
88
- (`InstalledManifest`: the kept `manifest.yml` when its sha holds, else the record's mirror), as do `SessionConfig`, `BundleSettingsCheck`, `BlockRenderers`, `Status`, `BundleCommand`'s
89
- status and diff, `Builder` and `InstalledCopy`. Their requires_chi checks are `InstalledManifest#requires_chi_failure`. `GuardrailWiring#rules_stamp` stats each bundle's
94
+ Readers of the installed state ask one verdict and keep only their reaction. The verdict is
95
+ `InstalledBundles.standings` (the walk) or `.standing(name)` (one record): a `Standing` whose `refusal` is
96
+ `:unreadable` (the record doesn't read) or `:too_new` (requires_chi), then, for a file chi loads, runs, serves or
97
+ reads, `InstalledBundles::Dir#file_refusal(:plugin | :scripts | :guardrails, file, recorded)` (`:file_missing`,
98
+ `:file_unrecorded`, `:file_changed`; each kind keeps today's order and words, so the same failure wins as before).
99
+ What each does with a refusal stays its own:
100
+
101
+ | Reader | `:unreadable` | `:too_new` | a file's refusal |
102
+ |---|---|---|---|
103
+ | `Plugin::Loader.load_bundle` | a failure that fails closed (required) unless its kept `manifest.yml` reads and names no required plugin (`#unreadable_required?`) | a failure (required for a guardrail plugin) | a failure, the refusal's text |
104
+ | `GuardrailWiring#bundle_rules` | a required failure | `#too_new_bundle_rules` (the rules loaded before stay) | a required failure per rule file |
105
+ | `ContextProviders.resolve` / `.any?` | skipped | skipped, `providers_too_new` logged once (only when it declares providers) | n/a |
106
+ | `ContextProviders.command_for` | not refused (a `manifest.json` that doesn't parse raises `JSON::ParserError`: D7; one that isn't an object runs: D8) | `Invalid` | `Invalid`, per recorded script |
107
+ | `BlockRenderers.for_installed` / `.script_path` | lists none | skipped | `Invalid` |
108
+ | `SessionConfig.availability` | left out | a note, only when it has a plugin (D2) | a note |
109
+ | `BundleSettingsCheck.warnings`, `BundleNeeds.entry_markers`, `MemoryCommand.entries` | skipped | still read (D1, D5) | n/a |
110
+ | `MemoryBundle::Status.plugin_status` | n/a | `requires_failure` | `missing`, else `modified` (D9) |
111
+
112
+ `InstalledBundles.claimants` skips an unreadable record off the record itself (`Record#error?`), so a claimant
113
+ check reads no manifest. `ContextProviders`' once-per-process log is a Set under a Mutex, like `GuardrailWiring`'s
114
+ kept-rules notice. The D rows are the plan's V2 decisions; until then each reaction is pinned as it is.
115
+ They read shas and state off the record, and
116
+ manifest data (requires_chi, needs, providers, renderers, settings) through `InstalledBundles::Record#manifest`
117
+ (`InstalledBundles::Manifest`: the kept `manifest.yml` when its sha holds, else the record's mirror), as do `SessionConfig`, `BundleSettingsCheck`, `BlockRenderers`, `Status`, `BundleCommand`'s
118
+ status and diff, `Builder` and `InstalledCopy`. The one requires_chi gate is `InstalledBundles::Manifest#requires_chi_failure`, which the runtime readers reach through `Standing` (`:too_new`). `GuardrailWiring#rules_stamp` stats each bundle's
90
119
  `manifest.yml` with its `manifest.json` and `guardrails/*`, so a changed requires_chi re-reads the rules. No reader
91
- calls `Manifest.new` on a kept file: `Manifest.tolerant` through `InstalledManifest` is the one read.
92
- A guardrail plugin (`plugin:` `required: true`) is known from `InstalledManifest#plugin_required` before
120
+ calls `BundleManifest.new` on a kept file: `BundleManifest.tolerant` through `InstalledBundles::Manifest` is the one read.
121
+ A guardrail plugin (`plugin:` `required: true`) is known from `InstalledBundles::Manifest#plugin_required` before
93
122
  `Plugin::Loader.load_bundle` builds it: the install records the flag in the record's `plugin:` (`PluginRef#required`,
94
123
  `Provenance#write`'s `plugin_required:`), and the kept manifest's flag is ORed with it, so a missing, edited or
95
124
  unparsable kept manifest.yml never drops it (an older chi's `PluginRef` ignores the key):
96
125
  its failure goes to the hook failures as required (`ExtensionLoad#load_plugins` passes them as `guardrail_failures:`),
97
126
  where the gate denies every tool call; a `chi.on(on_error: :fail_closed)` hook is wrapped `Hooks.wrap(policy: :deny)`.
98
- The checks live in `Plugin::Loader.load_bundle` (its `.sha_mismatch`; `.namespace_for` is the bundle's
127
+ `Plugin::Loader.load_bundle` asks the verdict (`InstalledBundles::Standing`, then `Dir#file_refusal(:plugin, …)`) and reacts (`.namespace_for` is the bundle's
99
128
  `Samagotchi::Bundles::<bundle>` module); the loading itself is `Plugin::Loader.register_file` (one
100
129
  plugin file: build, `register`, `commit!`), which raises instead of logging: the bundle test kit
101
130
  (`Samagotchi::Testing::Bundle`) loads a bundle's source through them, unchecked. `Samagotchi::Testing::Install` is the
@@ -106,9 +135,9 @@ bundle, or a SyntaxError's own line), which `Install` maps from the installed co
106
135
  back to the source dir.
107
136
 
108
137
  Class-file hooks (retired). A record an older chi installed may still have a `hooks` map and `hooks/*.rb`
109
- (`InstalledBundle#hooks`). Nothing loads them, and nothing announces them any more (the first turn, `chi bundle
138
+ (`InstalledBundles::Record#hooks`). Nothing loads them, and nothing announces them any more (the first turn, `chi bundle
110
139
  status` and `chi update` did from 0.158 to 0.166). A source with
111
- hooks is refused before its manifest is read (`Manifest::HooksRetired.refuse_source_files`, then `Manifest.read`),
140
+ hooks is refused before its manifest is read (`BundleManifest::HooksRetired.refuse_source_files`, then `BundleManifest.read`),
112
141
  strict or not, a dry run too; `ShippedUpdate`'s plan skips one the same way. Over such a record,
113
142
  after the plugin and scripts (so a refused install leaves them), `AssetInstaller#retire_hooks` copies every edited or
114
143
  unknown file under `hooks/` to the trash
@@ -217,7 +246,7 @@ copy is still there. Any other keeps its old base and mark, and the command exit
217
246
  `select_memories` (all but `index.md`/hidden; with `--files` the named ones + their overlays, else leaving out files
218
247
  another installed bundle owns) → `checksum_memories` → `installed_parts` (`Builder::InstalledParts`: the same-name
219
248
  installed bundle's rules, plugin, scripts, context providers, else the scope dir's `guardrails/`) →
220
- `stage_files` + `write_manifest` (requires_chi, needs, settings… from the installed bundle's `InstalledManifest`;
249
+ `stage_files` + `write_manifest` (requires_chi, needs, settings… from the installed bundle's `InstalledBundles::Manifest`;
221
250
  `trust_level` and `description` the CLI's, else that manifest's; a kept manifest's unknown keys carried, each with a
222
251
  `unknown_key_line` warning) in a temp dir → `write_out` (zip, tar, tgz, or a new/empty dir). An installed
223
252
  profile's name is refused (`refuse_profile!`): a build can't remake its includes.
@@ -284,7 +284,7 @@ long as the Engine (tools, hooks, the gate). The rules an edit gets wrong:
284
284
  `tool_refs` (`ToolResponse::SAVED_KEYS`, never sent) and `MessageParts#tool_part` re-checks them
285
285
  (`RowRefs.for_display`).
286
286
  - An unknown tool gets `ToolSurface#unknown_tool_error` ("Error: no such tool ...", never repeating the wrong name).
287
- - Edit and write: the file is diffed, and a memory's index line refreshed (`MemoryBundle::IndexSync`). At most
287
+ - Edit and write: the file is diffed, and a memory's index line refreshed (`MemoryIndex::Sync`). At most
288
288
  `MAX_IMAGES_PER_RESULT` images per result. Non-UTF-8 bytes are scrubbed.
289
289
  - The output cap (`max_tool_output_chars`, a `memory_read`'s `memory.read_max_chars`) cuts by the tool's
290
290
  `ToolOutputCut` policy; an execute's whole output is saved by `ToolOutputFiles` in `TurnContext#session_dir`. See
@@ -55,7 +55,7 @@ their viewer (The viewer, below), their show and stream are filtered (`Web::Part
55
55
  | **`store.sessions`** (the hub's projection) | every card | `store.update({sessions})` from app.js: `openSessionEvents` (`applySessionEvent`), `refresh` (the list fallback), `addCreatedSession`, `applyView` (re-sorted), `replaceSelectedCard` (`setLiveStatus` through `setStatus`, `readTurnEnd`, `setUsedMemories`), the stream's close (`withoutWorker`); `session_actions.js` (`setSessions`) | the store: `lists` and `infoBar`. **Always a new array**; an entry is replaced, never changed in place. `followSelectedSession` copies the open one's owner and worker (`fieldsFromCard`) and, when not streaming, its status (`setStatus(…, "hub")`) into `store.current` |
56
56
  | **Factory closures**: the `create*` factories (popovers, panels, views) | each component's own state: open-for, busy, error, its own fetched list | the factory | an `onChange` hook back into app.js, or a getter the factory reads at draw time |
57
57
  | **The history DOM** | the conversation as drawn (a running turn's reason bubble, `.bubble.said`, is live only: see A turn opened in the history): which turn a bubble belongs to (`data-turn-id`, `data-answer-turn`), what opens a turn (`TURN_PROMPT`, `bubbles.js`: a prompt or a wake's note, the same turns `Steer.turn_opening?` counts for a card's `turns_since`), an opening's id for a card's and the saved recap's stamp (`data-turn-id` on a prompt, `data-opening-id` on a wake's note or `/continue no`'s reason line; `card_stamps.js` places a snapshot's card after the stamped opening, `recap_stamp.js` the saved recap after the last turn it covers, each by its count (`turns_since`) only without one), kept command bubbles, which texts were shown, unnamed badges, folded answers and long prompts (`.folded`), Revise stamps (`data-revises` on a prompt; a Verify turn's `data-verify`) and the stacks' folded versions (`.stack-hidden`, `.stack-stub.open`); the switcher's version on view is `revise_stack.js`'s own (a copy `.stack-view` before the top answer, the top `.stack-swapped`; never stored) | `bubbles.js`, `cards_place.js`, `question_cards.js`, `turn_block.js`/`stage_view.js`, `answer_fold.js`, `revise_stack.js`, `stream_handlers.js` (a live `turn_completed`'s `revises` and `verify` onto its prompt) | read back as state: `turn_range.js turnElements` (one walker for a turn's elements), `keptCommandBubbles`, `seedSeenFromDom`, `nameUnnamedBadges`/`nameVerdictCards`, `answer_fold.js` and `revise_stack.js` (their observers decorate every path that fills `#history`; the stacks are `stacks()` of the stamps, read again on each change, never a store field), `history_reveal.js revealInHistory` (the one way a jump unfolds what hides its target) |
58
- | **A drawn turn** (`turn_drawings` of the full read) | every finished turn, as live drew it: `turnGroups` groups by the stamps only, a turn's stamped items (`drawn: <turn_id>`) one group, and `turnHistoryNodes` draws it by feeding its drawing's events to a live turn block offscreen (`turn_block.js drawnTurnNodes`: the block's own handlers, as the stage's), the stage's extras (a reminder, merged lines, a card that asks or warns) and end as live, then the answer, the merged lines and the steps' texts from their saved items (markdown, refs). Each of its top-level elements carries `data-drawn`: `cards_place.js` leaves that turn's in-turn CardStore entries (`of_turn`) to it, and a kept reminder bubble of that turn (`data-turn-id`) stays out after a resync. chi web sends a drawing for every finished turn (one made from its messages where live wrote none): `drawnGroup` pairs the record the end names (`end.record_id`, by place for a turn saved before turn ids), else by the turn's id, and the answer's `data-answer-turn` is the end's own `turn_id` only (a made-up id, `m…` or `…~N`, keys none: no Revise). Nothing is rebuilt from messages: an item that comes unstamped is a `plain` group drawn as a plain row of its text (its prompt or answer bubble, no steps), the running turn's as expected (`runningTurnId`, the show's `current_turn`: it has no line yet), any other a miss, marked `data-undrawn`, logged once per render (`console.warn`) and counted by the reload check (`undrawn`), never a throw; a drawing with no parts (a minimal line) draws its prompt, answer and end | chi web (the show) | `renderHistory`, the reload check's render |
58
+ | **A drawn turn** (`turn_drawings` of the full read) | every finished turn, as live drew it: `turnGroups` groups by the stamps only, a turn's stamped items (`drawn: <turn_id>`) one group, and `turnHistoryNodes` draws it by feeding its drawing's events to a live turn block offscreen (`turn_block.js drawnTurnNodes`: the block's own handlers, as the stage's), the stage's extras (a reminder, merged lines, a card that waited when it arrived, an answered question) in the order live left them for the history (`turn_settle.js settleOrder`, pure: from the drawing's `part_settled` and question events, whether the turn was opened, and whether a question had a lead-in) and the end as live, then the answer, the merged lines and the steps' texts from their saved items (markdown, refs). Each of its top-level elements carries `data-drawn`: `cards_place.js` leaves that turn's in-turn CardStore entries (`of_turn`) to it, and a kept reminder bubble of that turn (`data-turn-id`) stays out after a resync. chi web sends a drawing for every finished turn (one made from its messages where live wrote none): `drawnGroup` pairs the record the end names (`end.record_id`, by place for a turn saved before turn ids), else by the turn's id, and the answer's `data-answer-turn` is the end's own `turn_id` only (a made-up id, `m…` or `…~N`, keys none: no Revise). Nothing is rebuilt from messages: an item that comes unstamped is a `plain` group drawn as a plain row of its text (its prompt or answer bubble, no steps), the running turn's as expected (`runningTurnId`, the show's `current_turn`: it has no line yet), any other a miss, marked `data-undrawn`, logged once per render (`console.warn`) and counted by the reload check (`undrawn`), never a throw; a drawing with no parts (a minimal line) draws its prompt, answer and end | chi web (the show) | `renderHistory`, the reload check's render |
59
59
  | **The cards as data** (`card_registry.js`; app.js `cardRegistry`) | every question, continue offer and plugin card of the open session, keyed as `stage_waiting.js` keys them (`q:<id>`, `c:<id>`, `continue`): its kind and folded text (`card_kinds.js`), status (pending, answered, cancelled; resolved or dropped for the continue offer; asks or shown for a plugin card), `of_turn`, `opening_id`, step, `relayed_to` | `observeCards` around the stream handlers (outside the participant wrap: the page's handler first, then `apply`), so a read's replay feeds it too; `session_view.js renderSessionView` seeds it from the read right before the replay (`seed`: CardStore's listing, the pending question, the continue offer; it replaces), `forgetSession` resets it. Idempotent: a merge per key, a final status never back to pending, the first `of_turn`/`opening_id`/step kept, so seed then replay is what live holds. A question still pending at its turn's end is cancelled (the page cancels the card, no event comes) | an observer: nothing on the page draws from it; its one reader is the opt-in reload check (`reload_check.js`: this turn's entries against a registry seeded from a fresh read). `stage_cuts_parity.test.js` checks it against the stage's waiting cards at each cut, `card_registry.test.js` the events against each cut's seed and replay |
60
60
  | **What was opened of a running turn** (`stage_view_memory.js`, in `session_view.js`) | per session, for this tab: the cloud open, the steps opened in it, the working set's reader on an item; a Map of at most 20 sessions, nothing stored or sent (the peek isn't kept: it closes with its popover) | `session_view.js leaveSession`, from `session_sync.js select` and from `forgetSession` itself for the session it drew last (so the start page, `clearSelection`, keeps it too) before its reset (`captureView`); dropped by `endTurnView` | `renderSessionView`, once the read is drawn: put back (`applyView`) only when the read's running turn (`current_turn.turn_id`) is the one saved; taken either way |
61
61
  | **localStorage** (`storage.js` `readStored`/`writeStored`, guarded) | per-browser choices only; a session's view settings per session (`session_prefs.js`) | the module that owns the choice | read at start, a session's view settings again when its view is drawn (see Storage keys) |
@@ -587,6 +587,23 @@ none. The replayed card opens the turn as live; a question answered earlier in t
587
587
  replayed `question_answered`, and `releaseHeldWait` reads a pending card, not the `waiting` class the replay's one task
588
588
  hasn't refreshed yet.
589
589
 
590
+ **After the turn's end, reloaded:** a drawn turn's pieces beside its block come back in the order the rows above left
591
+ them, live (`turn_settle.js settleOrder` over the drawing's events): a reminder or a merged line where it arrived; a
592
+ question with a lead-in at its request (the turn opens first: what the extras held goes to the history before the
593
+ lead-in, as `openTurn` does), one without at its answer; a card that waited when it arrived (its arrival
594
+ wait is the drawing's first `part_settled` for it, `Bridge::TurnAccumulator#fold_card`: the card part keeps only its
595
+ latest version) where it stopped waiting while the turn was opened, else at the hand-off; what still waits at the end
596
+ goes last (a warning with the block's kept cards). A question is drawn as an empty slot (`turn_block.js questionSlot`,
597
+ `data-question-slot`, stamped `data-drawn`) that `cards_place.js placeResolvedQuestion` fills with the resolved card
598
+ (its lead-in as before); a turn drawn without its question events (an older drawing) gets today's place (before the
599
+ lines steered after it and the answer), and `placeSnapshotCards` drops a slot no question came for. `history_shape.js`
600
+ reads an empty slot as a `question` item, which the reload check drops with the cards. A drawing written before
601
+ `settle` parts orders its cards by their latest version. **Mid-turn**, a reload or a join still can't say when a card
602
+ stopped waiting (the replay has no cards; the snapshot's are upserted after it): `stage_cuts_parity.test.js` lists
603
+ those differences. The approval question is asked after its call's `tool_call_started` (`ToolRunner#run`:
604
+ `settle_ask` runs after the row); a `before_tool_call` hook's question is asked before it (in the gate's `evaluate`),
605
+ where live shows no lead-in but the reload gives it one (not fixed).
606
+
590
607
  ## Frames
591
608
 
592
609
  During a turn the cost is frames, not code: JS, layout and style are each a few percent of a core, while an animation
data/docs/plugins.md CHANGED
@@ -511,6 +511,9 @@ chi.on(:before_tool_call, priority: 10, on_error: :fail_closed) { |event, _ctx|
511
511
  to load (a sha256 that differs, an unmet `requires_chi`, a raise in the file
512
512
  or in `register`) is a **required guardrail failure**: every tool call is
513
513
  denied until it is fixed ([guardrails.md](guardrails.md#failing-closed)).
514
+ If manifest.json doesn't read, chi treats the bundle as required unless the
515
+ kept manifest.yml reads and names no plugin or a plugin without
516
+ `required: true`; reinstall the bundle to fix it.
514
517
  Without the flag a fail-closed hook still denies the call it raises on, but
515
518
  a load failure denies nothing; `chi bundle check` warns (`fail-closed`) and
516
519
  the log says so (`plugin_fail_closed_unrequired`).
@@ -985,7 +988,9 @@ In the web, a turn's block collapses when the turn ends. A `:warn` card, and
985
988
  any card of a turn that ended without completing (cancelled, failed, the
986
989
  worker gone), then moves out of the block, after the turn's end line, so it
987
990
  stays in sight; a reload puts it in the same place. An `:info` card of a
988
- completed turn stays in its step.
991
+ completed turn stays in its step. A card that asks (check-in's) sits beside the block, in the order it showed live:
992
+ where it stopped asking, or after the turn's answered questions when it still asked at the end; a reload puts it
993
+ there too.
989
994
 
990
995
  Between turns, a card goes above the first turn prompt after it, live and
991
996
  after a reload. A failed turn whose prompt went back to its sender isn't a
@@ -1451,7 +1456,13 @@ that calls it, or for a real external bundle that does. No method on the chance
1451
1456
  `check_hint!`, `paired_lines`, `transport_line`, `peer_dir` and
1452
1457
  `setup_paragraph` (optionally `skill_substitutions`), and sets `NAME`,
1453
1458
  `APP`, `COMMAND`, `USAGE`, `OUTBOX` and `SCRIPTS_DIRS`. These constants are
1454
- read as `self.class::X`. See the [claude-peer](bundles.md#the-claude-peer-bundle) and
1459
+ read as `self.class::X`. The base names each send: `Peer.send_id(kind, title, text)` (`s-` and 6 hex
1460
+ of SHA-256 over the args as given) is the message's second line (`ref: <id>`), the tool row's `peer` ref
1461
+ (display only, no actions; computed from the args before the call runs, so a send that then fails has it too)
1462
+ and the last send's `id`; the peer's answer echoes it as `re` ([context.md](context.md#the-command-contract)).
1463
+ Successful sends and transport failures are recorded in the session's peer exchange log; answer pushes add
1464
+ summaries, not answer texts. The log does not enter the model's context.
1465
+ See the [claude-peer](bundles.md#the-claude-peer-bundle) and
1455
1466
  [codex-peer](bundles.md#the-codex-peer-bundle) bundles.
1456
1467
  3. `Samagotchi::Tools::ToolIndex::Tool` and `Samagotchi::Tools::ToolIndex::Group`
1457
1468
  values, `Samagotchi::Tools::ToolIndex.schema_note` and
@@ -1468,7 +1479,7 @@ that calls it, or for a real external bundle that does. No method on the chance
1468
1479
  and [bundles.md](bundles.md) document them — `name`, `version`, `scope`, `description`, `files`, `hooks`,
1469
1480
  `trust_level`, `plugin`, `requires_chi`, `requires_chi_next` (shipped bundles only: the release tooling
1470
1481
  reads it, chi doesn't), `needs`, `scripts`, `context_providers`, `block_renderers`, `includes`,
1471
- `session_settings`, `settings`. Those are `Manifest::KEYS`; `Manifest::SINCE` is the chi release each
1482
+ `session_settings`, `settings`. Those are `BundleManifest::KEYS`; `BundleManifest::SINCE` is the chi release each
1472
1483
  key or shape first worked in, and the docs don't copy it — the code is its truth.
1473
1484
  - A key keeps its meaning. A new key gets a `SINCE` entry and a CHANGELOG line, and an older chi says
1474
1485
  it ignores it (`unknown-key`).
data/docs/releasing.md CHANGED
@@ -32,7 +32,7 @@ can run the whole release; the user approves the notes before the tag and the
32
32
  - a new `ctx.*` / `chi.*` call a plugin may make gets its release's version in `Plugin::Api::SINCE` once
33
33
  released (`chi bundle check`'s `requires-chi-floor` reads it); an unreleased one waits there as an `# Unreleased` comment, and
34
34
  `release:bump` moves each call it names up with the new version (`release:check` fails while a comment is left);
35
- - a new manifest key or shape gets its release's version in `Manifest::SINCE` the same way (check's
35
+ - a new manifest key or shape gets its release's version in `BundleManifest::SINCE` the same way (check's
36
36
  `requires-chi-floor` reads it for the manifest too), waits as an `# Unreleased` comment while unreleased,
37
37
  and `release:bump` moves it up with the new version the same way;
38
38
  - a new shipped bundle joins a profile (`includes:` in `core` or `dev`; a
@@ -76,8 +76,8 @@ as the GitHub release body.
76
76
  | `rake lint` / `rake lint:fix` | RuboCop over the repo (must report no offenses; CI runs it) / its safe autocorrect (`rubocop -a`). |
77
77
  | `rake gem:validate`, `gem:build`, `gem:install`, `gem:clean` | Check the gemspec; build the gem into `pkg/`; build and install it locally; remove the built gems. |
78
78
  | `rake release:draft_changelog` | A draft Unreleased section from the commit subjects since the last tag, grouped. Stdout only. |
79
- | `rake release:bump[X.Y.Z]` | VERSION, the system manifest, Gemfile.lock, CHANGELOG, a compatibility corpus at `spec/compat/X.Y.Z/` written through the current state writers (with `wire/`: a real Engine and Bridge's replies, recorded twice and refused if the two differ), refreshed `spec/shared/compat_wire/*.json` fixtures, `spec/web/public/exports_baseline.json` rebuilt from the public modules, and `requires_chi: ">= X.Y.Z"` for each bundle marked `requires_chi_next` (the marker dropped), then a profile left below a member's `requires_chi` raised to it, with a patch bump of its version (none when it moved since the last tag) and named in the CHANGELOG's "Update with `chi update`" line, and each entry an `# Unreleased` comment in `Plugin::Api::SINCE` or `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
- | `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). |
79
+ | `rake release:bump[X.Y.Z]` | VERSION, the system manifest, Gemfile.lock, CHANGELOG, a compatibility corpus at `spec/compat/X.Y.Z/` written through the current state writers (with `wire/`: a real Engine and Bridge's replies, recorded twice and refused if the two differ), refreshed `spec/shared/compat_wire/*.json` fixtures, `spec/web/public/exports_baseline.json` rebuilt from the public modules, and `requires_chi: ">= X.Y.Z"` for each bundle marked `requires_chi_next` (the marker dropped), then a profile left below a member's `requires_chi` raised to it, with a patch bump of its version (none when it moved since the last tag) and named in the CHANGELOG's "Update with `chi update`" line, and each entry an `# Unreleased` comment in `Plugin::Api::SINCE` or `BundleManifest::SINCE` names moved into the table at X.Y.Z (the comment dropped). No commit; commit the corpus, fixtures and baseline with the release. |
80
+ | `rake release:check` | Clean tracked tree, VERSION == system bundle, a CHANGELOG section, no `requires_chi_next` left, no `# Unreleased` comment left in `Plugin::Api::SINCE` or `BundleManifest::SINCE`, `bundles:check`, `rake lint` (RuboCop) + `npm run lint` (the web frontend's ESLint), rspec (both roots: `spec` and the bundles' own `spec/`) + `rake bundles:specs` + npm test, `gem build`, then a clean install into a temp GEM_HOME that runs `chi --version`, `chi self` and `chi bundle list` with a temp HOME. Needs the network (gem dependencies). |
81
81
  | `rake release:notes[X.Y.Z]` | Prints the CHANGELOG section (default: the current VERSION). |
82
82
 
83
83
  ## Runbook
data/docs/scheduling.md CHANGED
@@ -248,6 +248,10 @@ its descendants, and archived sessions are outside the retention sweep
248
248
  count. The `anchor` is never pruned: it is the chain's root, the id the user and
249
249
  the coordinator remember, and `last:<anchor>` must keep resolving.
250
250
 
251
+ Schedule prune leaves the deleted links' background tasks running: a later link
252
+ may still use a server started by an earlier link in the same project. Continue
253
+ does not yet transfer task ownership.
254
+
251
255
  The oldest kept link still has `continues` naming a link that is gone. The walks
252
256
  follow `continues` forward, so nothing breaks; the web's `↩ #N of M` chip counts
253
257
  from the surviving root (pruning renumbers the links) and says "earlier links
data/docs/sessions.md CHANGED
@@ -2,6 +2,10 @@
2
2
 
3
3
  Sessions are plain files — no DB. Each session is `~/.local/state/samagotchi/sessions/<uuid>.json` (XDG-aware via `XDG_STATE_HOME`) plus a sidecar dir `<uuid>/` with `input/`/`notes/`/`output/`/`owner.lock`/`bridge.json` (`Session.session_dir`), `turn_drawings.jsonl` once a turn ended with a Bridge or in a one-shot run (each finished turn as live drew it, which the web's reload draws: [bridge.md](internals/bridge.md#turndrawings); a fork starts with its parent's lines for the turns its seed keeps unchanged, a continue with none: its turns, and any without a line, are drawn from their messages), and `tool_output/` once a long `execute` result was cut: its whole output, which the cut result names (`ToolOutputFiles`, the newest 50 kept; see [Tool output guardrails](internals/tool-output-limits.md#the-runners-cut-max_tool_output_chars)). Its keys are in [the Session file table](#session-file). A file from before `used_memory_names`, `preloaded_memory_names`, `muted_memory_names`, `parent_id` or `continues` reads those as empty lists, no parent and no previous link.
4
4
 
5
+ The sidecar's `peer_exchanges.jsonl` records peer sends, transport failures
6
+ and answer summaries, never answer text. It stays with the previous link on a
7
+ continue; the new link starts empty. See [context storage](context.md#storage).
8
+
5
9
  **Message times:** an entry of `messages` may carry `at`, when it happened: a local-offset ISO time with milliseconds (`2026-10-24T14:32:05.120+02:00`). User prompts, lines merged into a turn and steers, reminders, context and task notes, and the model's replies have one (a note's is its `created_at`); tool results, `!cmd` messages and chi's own turn notes don't, nor does anything saved before chi stamped messages (no backfill). It is for the UIs only (the gap dividers, a bubble's time): it never goes to the model, so it changes nothing in the requests or their prompt cache. The one time the model reads is the reminders': due reminders go into a turn as a system message headed `[SYSTEM: REMINDERS DUE 2026-10-24 14:32 local]` (the turn's local time; `ReminderQueue#inject!`), written into the saved content then, so a later request sends the same text.
6
10
 
7
11
  **Verify verdicts:** a web Verify turn stamps its opening user message with `verify: {turn_id, quote}` (the selected source turn and quote; metadata only, never added to the prompt). When that turn completes and the final assistant reply's last non-empty line is a valid `Verdict: confirmed|refuted|unclear — <reason>`, the session file appends `{anchor: {turn_id, quote}, verdict, reason, by, check_turn_id, at}` to its optional `verdicts` array. `by` is the turn's author (nil for the owner), `check_turn_id` names the Verify turn, and `at` is its timestamp. The array is append-only; older files without it have no saved verdicts. An `unclear` verdict can be checked again by **Verify fresh** (a delegate child that gets only the claim; see *Delegating*): its verdict is appended to the parent's `verdicts` with `fresh: true`, `of` (the verdict it checked again) and `child_id`, from the parent's `fresh_verdicts/` dir, which its worker takes between turns. Verdicts are display state: none enters a prompt.
@@ -23,6 +27,8 @@ Sessions are plain files — no DB. Each session is `~/.local/state/samagotchi/s
23
27
 
24
28
  A session is deleted if **expired by age OR overflow by count** (unless `keep_status` or the live-owner guard: a session a worker or `chi` still has open is never pruned). A session's `status` is its turn state (`idle`/`running`), not whether a worker is alive. Orphan dirs without a `*.json` are never deleted, except skeleton-only ones (see *Empty sessions*). Deletion removes its `*.json` and sidecar dir under the deleting owner lock, along with its plugin state, attached context, participant grants, System 1 runs and context-candidate records. Explicit delete and retention use the same cleanup path. Set both `DAYS=0` and `MAX=0` to retain forever.
25
29
 
30
+ Retention and manual prune/clean silently stop each deleted session's verified background tasks under its deleting lock, with `by: retention` (`stopped_by_retention`). Sessions are processed sequentially, their tasks in parallel. Unverified or unreadable tasks are not signalled; stops and failures are logged per task as `retention_task_stopped` / `retention_task_not_stopped`, without commands. A scratch session's own cleanup does the same with `by: scratch` and `scratch_task_stopped` / `scratch_task_not_stopped`.
31
+
26
32
  **Worker idle exit:** a background worker (plain `chi`, Web UI sessions) exits after `SAMAGOTCHI_SESSION_IDLE_EXIT_MINUTES` (`session.idle_exit_minutes`, default `30`, `0`=never) with no turn running or queued, no client on its stream (an open web tab or attached terminal keeps it), no reminder registered, no background task it watches for a [finish wake](internals/background-tasks.md#finish-wake) still running or waiting for its wake turn (with `session.task_wakes: wake`; not one whose turn you stopped) and no continue offer (the step-limit question) waiting for an answer. It removes `bridge.json` and frees `owner.lock`; the next prompt or `--attach` wakes a new worker (`WorkerIdleExit`, `WorkerBoot.run_session_loop`). As its Bridge stops, the worker marks the lock leaving (`OwnerLock#mark_leaving`: `leaving_at`, and `leave_wait`, its `recap.timeout`), since it keeps the lock while it writes the recap on leave: an `--attach` or `--resume` meanwhile (here, or a remote one through chi web's wake) prints `(waiting for the session to finish its recap…)` (`LaunchMode::RECAP_WAIT`) and waits for the release, up to that budget plus `OwnerLock::LEAVE_MARGIN` (5 s), before starting the new worker (`OwnerLock.await_release`). A lock held by a worker that isn't leaving (a live one, a stuck one) is left as before. A client can also ask the worker to exit right away (Bridge `POST /session/:id/exit`; `/exit` in an attached terminal does, `/detach` doesn't): the same rules apply without the timeout (even with `0`), and the asker's own stream doesn't count. The reply names what keeps it up (for background tasks, which ones and how to stop them). When every hold is one the user can stop — reminders, a watched task still running, a delegate with a live worker — the 409 also carries `holds: [{kind:, items: [{id:, label:, detail:}]}]` (a reminder's detail is its schedule, `every 20m`/`every 1h`, `, due now` when it is already due), and an attached terminal asks what to do with them; its "stop them and exit" posts `{"stop": "all"}`, which clears the reminders, stops those tasks (`TaskRuntime.stop_task`, as `task_stop`) and stops those children (`SessionManager.stop_session`) before leaving, re-checking first that nothing the user can't stop appeared meanwhile (`HoldStop`). A delegate counts only for that ask: it never holds the idle exit, and an exit that deletes or archives the session does not ask about it. The session's status stays as it was, not `stopped`. With `"restart": true` (a worker whose sidecar lists the `restart` feature) the worker hands the session to a new worker on the newest chi installed: it leaves, then starts its successor once its lock is free, keeping even an empty session and writing no recap. Clients' streams don't hold a restart (a web tab and an attached terminal reconnect to the new worker); what would be lost does: a turn running or queued, a continue offer, a question or approval waiting, a `/btw` (or another anytime command) still running, a delegate's approval relay open or settled in the last 10 minutes, and background tasks this conversation started that still run (`WorkerIdleExit#hold_for_restart`; 409 `held` with `reason`). Reminders go along: as it leaves, the worker writes them to `<id>/reminders.json` (0600: `session_id`, `written_at`, and each reminder's id, name, description, interval and next fire as wall-clock time; `ReminderCarry`), and its successor reads and deletes the file as it starts, before its idle scheduler runs. A restored reminder keeps its id and schedule; one that came due meanwhile fires once at once, and one further ahead than its interval (a clock that jumped) is due one interval from now. The file counts only for the same session within 2 minutes of `written_at`, and not once the session is stopped: otherwise it is deleted unread (log `reminders_carry_dropped`, at warn unless the session was stopped). A stop that lands while the worker leaves for a restart wins: the worker writes no file, and no successor starts (`WorkerBoot.run_session_loop`, log `restart_dropped`). So does one that lands as it leaves any other way (an idle exit, `/exit`, a signal) with input queued or delegate reports waiting: no new worker un-stops it (log `respawn_dropped`), and what waits stays for the next start. A person's send after the stop (chi send, a web tab, a terminal) still un-stops it, as a person's send always does (see *Who may wake a session* below): one that reaches a leaving worker clears the stop, so the leave's new worker runs it (log `send_unstopped_leaving`); an archive deletes the file of each session it archives. Once an exit or restart is taken (claimed before a stop-all stops anything), the first one decides how the worker leaves: a later request of the same kind is answered as that exit, one of another kind (a stop-all from another terminal after a restart, chi web's "Restart workers" after a `/exit`) gets 409 `held` with `reason` `leaving_exit`, `leaving_delete` or `leaving_restart`, and a restart says it was refused rather than "restarted". A write that fails keeps the worker up with its reminders (log `reminders_carry_failed`), and the caller reports no new worker. A reminder already due when the restart is asked runs its turn first, so the restart's wait (10 s) may report no new worker yet though the hand-off follows. A worker from before this still refuses a restart for its reminders (409 `reminders`). Only an asked restart carries them: the fallback's TERM (a worker that can't be asked, below), a stop, an idle exit (which reminders hold anyway) and a crash drop them as before. What lives only in the worker's memory goes: the event history a late client replays, the kept `/btw` answers, a plugin's in-memory state.
27
33
 
28
34
  **Empty sessions:** a session nothing happened in is deleted when it is left, so `chi` → `/exit` leaves no trace. Empty means: no messages, no turn tried (a failed turn leaves a `last_prompt` and keeps it), no memory used, no pending question, nothing in `input/`, `notes/` or `images/`, nothing in its dir beyond the worker's skeleton, mode `assist`, and the default model. A session on another model (`/model`, `--model`) counts as prepared and stays (`SessionManager.discardable?`). The worker checks as it idle-exits or leaves on a client's request and deletes it once its lock is free, checking again first and once more under the delete's lock (a prompt or note that went in before that keeps it). The attached `/exit` then says `Detached; the session is empty: it will be discarded if nothing arrives before its worker stops.` (a note or prompt landing first keeps it). The retention sweep catches those killed first: empty sessions over an hour old with no live owner, whatever `DAYS`/`MAX`, and skeleton-only dirs with no `*.json` (removed as a delete removes, every session store, under the session's lock: a worker or a start that took the session since the check keeps it, and so does one whose file or content was written meanwhile, read again under that lock). `session.keep_empty: true` (env `SAMAGOTCHI_SESSION_KEEP_EMPTY`) turns all of it off.
@@ -43,13 +49,13 @@ A new session field is one `Session::FIELDS` row, plus a `SessionSetup` member w
43
49
 
44
50
  **Stopping a worker:** `chi sessions stop ID` marks the session stopped (an `<id>/stopped` file holding when, `{"at"}`, not a session.json field, which a worker saving at that moment would write over; a resume removes it), sends its worker TERM, then CONT (a stopped worker, SIGSTOP or Ctrl-Z, runs its TERM handler only once continued, so it leaves at once instead of outliving the wait), and waits (up to 10 s) until the worker has let go of `owner.lock`. A running turn is canceled over the Bridge first, with reason `session_stopped` (the turn's line ends "(session stopped)", its note says `cancelled (session-stopped)`, and a command it was running says "stopped as the session was stopped"; a bare signal to the worker makes it "stopped by a signal to chi"; an older worker takes the reason as `manual`); the TERM stops whatever still runs as a Stop with reason `signal` and saves it (a spawned worker traps TERM, HUP and INT: `WorkerSignals`; a turn not ended within 3 s, 0.5 s after a stop or a second signal, is cut and the session saved as it was), and a stopped worker still saves its kept turn, since the marker, not the saved status, says stopped. Any TERM, HUP or INT does the same to a worker outside a stop: it leaves (log `worker stop reason=signal`) and the next send wakes a new one, so a `chi --resume ID` right after spawns a fresh worker. That is also how to restart a worker still running an older chi, which the attached terminal reports when a command or a question dismiss gets a 404, and the web when an answer, a dismiss, a command or a cancel does (`501 not_supported`; `BridgeClient.stale_worker_message`). A command this chi has that the older worker doesn't (`/llm-context`, the web's ⚙ panel, against a 0.39.0 worker) says the same, not `not a session command` (`SessionCommandCatalog.builtin_name`); a typo keeps its `400 unknown_command`. The web's `POST /api/sessions/:id/stop` waits the same way, for 2 s (the page's Stop shows the stop at once), or for the body's `wait` up to the same 10 s (`SessionManager::STOP_WAIT`): `chi --remote NAME sessions stop` sends it, so it waits as long as here. Before that stop, the page's `stop session` button asks what the worker still has that the user can stop: `GET /api/sessions/:id/holds` (owner-only) answers the worker's `holds` — the same list the exit ask's 409 carries — always an array, empty when there is no live worker, one from before the route, or one that did not answer. With something, a sheet (a bottom sheet on a phone, a popover at the button otherwise — `stop_sheet.js`) lists them, at most three of a kind named and `+N more`, and offers **Stop all** (`POST /api/sessions/:id/holds/stop` → `HoldStop#stop_all`, then the stop), **Stop session only** (the stop exactly as it was) or **Cancel**. Nothing to ask about is the plain confirm, one tap as before. Both buttons stay because a stop only TERMs the worker: its reminders die with it (a stop also deletes a restart's `reminders.json` no successor took yet, so a later resume doesn't bring them back), while a background task and a delegate are their own processes and keep running. A delete or an archive differs: it never leaves a task the session started running unasked (*Deleting a session*: refused, or `--stop-tasks` stops it), where Stop's "Stop session only" does. A command sent during a turn that waits for its end (`/model X`, `!cmd`; see *Typing during a turn* in [cli.md](cli.md)) and hasn't run when the worker leaves (a stop, a crash) is answered `command_ran {status: "dropped"}`, so no UI keeps showing it waiting.
45
51
 
46
- **Deleting a session:** `chi sessions delete ID...`, `/exit --delete` in a terminal and the Web UI's delete all go through `SessionManager.delete_session`: it resolves a unique prefix, removes `<id>.json` and the whole `<id>/` dir, and returns what it removed. A session a one-turn `chi --non-interactive` run has (`owner.lock` kind `tui`) is always refused. One a worker runs is refused unless the caller asks to stop it: then it stops the worker as `chi sessions stop` does and deletes once `owner.lock` is free (`--force` on the CLI, 10 s; the web page always, 2 s; `/exit --delete` after the worker agreed to exit, 10 s). A worker that outlives the wait leaves the session in place. A session whose worker is being started (the `<id>/starting` marker) is refused or stopped the same way, and the files go while the delete holds `owner.lock`, so a worker can't take the session in the middle; a worker that still had it loaded doesn't write it back. While the delete holds it (kind `deleting`), every delivery is refused: a message (`chi send`, the web, a schedule, a delegate, a plugin, a participant) gets 409 `session_deleting`, "the session is being deleted", and a send that read the session before the lock and wrote after it takes its file back and says the same (unless a worker took the file meanwhile: then it is delivered); a note is refused as for a gone session, and a delegate's ring, a push and a fresh verdict are not written. The web's route is `DELETE /api/sessions/:id?force=true` (the page sends `force`; without it a live worker's session is 409 `worker_running`, as the CLI without `--force`; 200 `{status: "deleted", session_id, stopped, unarchived, moved_back}`; `deleted` and `left_running` too; 409 with the refusal's reason as its code; 404). A schedule's target, anchor or head is refused (`scheduled`, naming the schedule): deleting a head would make the schedule fall back to an archived link. A user's delete (these three, `revive_previous:` and `refuse_continuing:` on `delete_session`) also knows about chains (`SessionChain::Delete`, *Session chains* → Deleting a link): it is refused while a continue of the session, or of the previous link it would bring back, is under way (`continuing`), and deleting a chain's newest link undoes its continue (D2/D5 below), the ids it brought back in `unarchived` and the delegates it gave back in `moved_back`. A previous link brought back is aged for retention from then on (`unarchived_at`) and has no participants (the archive ended them, and an unarchive doesn't bring them back). The scratch cleanup, the empty-session discard, the failed-continue rollback and a schedule's prune delete plainly; the retention sweep removes files directly (`remove_files`). **Background tasks still running:** a user's delete (these three, and `chi sessions delete`) asks first when tasks the deleted sessions started (their `task_create` tasks and the `execute` runs handed over at their limit, read from each session's transcript and `<working_directory>/tmp/tasks/<id>/task.json`: `SessionManager::RunningTasks`) still run: it is refused before anything changes (`tasks_running`), and the CLI's `--stop-tasks`, the web's `stop_tasks=true` (the delete's and the chain delete's query) stop them first (`stopped_by_user`, TERM then KILL after 3 s, all at once, about 4 s at most), under the deleting lock, after the starting-marker re-check, so no worker takes the session meanwhile; that last check refuses a task that started since the first (`worker_stopped: true` when the worker was stopped by then). One rule, fail-safe: a task whose pid still leads the group chi started at the start time it recorded is *running*; one whose record has no start time (before 2026-10-09) or whose start time reads nothing now, while its pid leads a group, is *unverified* ("may still be running"); a `task.json` that doesn't read is *unreadable*. All three refuse; a stop signals only the running ones (an unverified pid may belong to another process now) and reports the rest as not stopped, then deletes. A record left marked running whose pid is gone (a crashed worker's) isn't listed. The 409 is `{error: "tasks_running", reason, op: "delete", detail, session_id, tasks: {running, unverified, unreadable}, worker_stopped, stopped_worker}` (`stopped_worker`: whose worker the delete stopped before the last check refused), each task `{session_id, id, command}` (`links` too for a chain delete's other links); the 200 gains `tasks_stopped`, `tasks_not_stopped` and `tasks_ended` (empty unless stopped). A session's file gone (its folder left) has no tasks. Automatic deletes (the retention sweep, the scratch cleanup, the discard, the rollback, a schedule's prune) leave tasks running as before.
52
+ **Deleting a session:** `chi sessions delete ID...`, `/exit --delete` in a terminal and the Web UI's delete all go through `SessionManager.delete_session`: it resolves a unique prefix, removes `<id>.json` and the whole `<id>/` dir, and returns what it removed. A session a one-turn `chi --non-interactive` run has (`owner.lock` kind `tui`) is always refused. One a worker runs is refused unless the caller asks to stop it: then it stops the worker as `chi sessions stop` does and deletes once `owner.lock` is free (`--force` on the CLI, 10 s; the web page always, 2 s; `/exit --delete` after the worker agreed to exit, 10 s). A worker that outlives the wait leaves the session in place. A session whose worker is being started (the `<id>/starting` marker) is refused or stopped the same way, and the files go while the delete holds `owner.lock`, so a worker can't take the session in the middle; a worker that still had it loaded doesn't write it back. While the delete holds it (kind `deleting`), every delivery is refused: a message (`chi send`, the web, a schedule, a delegate, a plugin, a participant) gets 409 `session_deleting`, "the session is being deleted", and a send that read the session before the lock and wrote after it takes its file back and says the same (unless a worker took the file meanwhile: then it is delivered); a note is refused as for a gone session, and a delegate's ring, a push and a fresh verdict are not written. The web's route is `DELETE /api/sessions/:id?force=true` (the page sends `force`; without it a live worker's session is 409 `worker_running`, as the CLI without `--force`; 200 `{status: "deleted", session_id, stopped, unarchived, moved_back}`; `deleted` and `left_running` too; 409 with the refusal's reason as its code; 404). A schedule's target, anchor or head is refused (`scheduled`, naming the schedule): deleting a head would make the schedule fall back to an archived link. A user's delete (these three, `revive_previous:` and `refuse_continuing:` on `delete_session`) also knows about chains (`SessionChain::Delete`, *Session chains* → Deleting a link): it is refused while a continue of the session, or of the previous link it would bring back, is under way (`continuing`), and deleting a chain's newest link undoes its continue (D2/D5 below), the ids it brought back in `unarchived` and the delegates it gave back in `moved_back`. A previous link brought back is aged for retention from then on (`unarchived_at`) and has no participants (the archive ended them, and an unarchive doesn't bring them back). The scratch cleanup, the empty-session discard, the failed-continue rollback and a schedule's prune delete plainly; the retention sweep removes files directly (`remove_files`). **Background tasks still running:** a user's delete (these three, and `chi sessions delete`) asks first when tasks the deleted sessions started (their `task_create` tasks and the `execute` runs handed over at their limit, read from each session's transcript and `<working_directory>/tmp/tasks/<id>/task.json`: `SessionManager::RunningTasks`) still run: it is refused before anything changes (`tasks_running`), and the CLI's `--stop-tasks`, the web's `stop_tasks=true` (the delete's and the chain delete's query) stop them first (`stopped_by_user`, TERM then KILL after 3 s, all at once, about 4 s at most), under the deleting lock, after the starting-marker re-check, so no worker takes the session meanwhile; that last check refuses a task that started since the first (`worker_stopped: true` when the worker was stopped by then). One rule, fail-safe: a task whose pid still leads the group chi started at the start time it recorded is *running*; one whose record has no start time (before 2026-10-09) or whose start time reads nothing now, while its pid leads a group, is *unverified* ("may still be running"); a `task.json` that doesn't read is *unreadable*. All three refuse; a stop signals only the running ones (an unverified pid may belong to another process now) and reports the rest as not stopped, then deletes. A record left marked running whose pid is gone (a crashed worker's) isn't listed. The 409 is `{error: "tasks_running", reason, op: "delete", detail, session_id, tasks: {running, unverified, unreadable}, worker_stopped, stopped_worker}` (`stopped_worker`: whose worker the delete stopped before the last check refused), each task `{session_id, id, command}` (`links` too for a chain delete's other links); the 200 gains `tasks_stopped`, `tasks_not_stopped` and `tasks_ended` (empty unless stopped). A session's file gone (its folder left) has no tasks. The retention sweep and scratch cleanup stop verified tasks silently; the empty-session discard, failed-continue rollback and schedule prune leave them running.
47
53
 
48
54
  <a id="archiving-a-session"></a>**Archiving a session:** `chi sessions archive ID...`, `/archive` in a terminal and the Web UI's `archive` go through `SessionManager.archive_session`: it writes `<id>/archived` (`{"archived_at": …}`; not a session.json field, which every save rewrites) for the session and its delegated children. `Session.list` leaves archived sessions out unless `include_archived:`, and everything built on it follows: `chi sessions list` (`--archived` shows them, `[archived]`), the summaries (`--live`, json/tsv, the desktop panel, the agent's `list_sessions`) and the retention prune, which neither deletes nor counts them against `max_count`. `children_of` (max_children, `delegate_result`) still sees them, and `--resume`/`--attach ID`, `chi send`/`chi note ID` reach them as before, except that `chi send` and `chi note` to a link that was continued go to its chain's newest link (*Session chains*). Refused: a turn running in the session or in one of its children (naming the child; 409 `busy` on the web), a prompt queued in `input/` (it would run on the next resume) or a live worker's step-limit question still open, in it or a child (409 `busy` too), a one-turn `chi --non-interactive` run owning it (`owned_by_tui`), a `chi scratch` session (`scratch`). A live idle worker is stopped first, and the marker is written even if it is still shutting down. Input a human typed brings a session back (`{"unarchived_at": …}`): a prompt from the web, an attached terminal or `chi send` (origin `web:*`, `tui:*`, `cli:send`, its own first prompt: `spawn:first`; input naming no sender doesn't), steering merged into a running turn, a `/continue` answer or a question answered (the step-limit question too); a delegate's follow-up, a plugin's turn, a reminder, the idle recap, a note and just opening it don't. A child's input brings only the child back. The retention sweep ages an unarchived session from when it was unarchived, so unarchiving an old session doesn't let the next sweep take it. `/archive` leaves the session first, as `/exit` does, then archives it: in an attached terminal the worker is asked to exit (one that stays up for another UI is stopped by the archive; a running turn, a queued prompt or an open step-limit question refuses it), and an empty session is discarded instead; `chi scratch` refuses it. Typed while a turn runs, `/archive` waits for the turn's end (an attached terminal for the commands queued behind it too) and then archives. `chi sessions unarchive ID...` and the web's `unarchive` bring back the whole family. **Background tasks still running** in the session or a delegate refuse an archive as they refuse a delete (*Deleting a session*: the same rule and listing), before anything changes: 409 `tasks_running` (not `busy`, so an older client doesn't say "a turn is running"), `op: "archive"`. `chi sessions archive --stop-tasks`, or the archive route's body `{"stop_tasks": true}`, stops them first: after the tree's live workers were stopped and let go (or the wait ran out: such a worker's own waiter then records the stop from the `stop_requested_by` flag on disk), and before the marker; the 200 gains `tasks_stopped`, `tasks_not_stopped` and `tasks_ended`. An archive takes no lock for it. Undo (unarchive) doesn't restart them. Web routes: `POST /api/sessions/:id/archive` (200 `{status, session_id, archived, stopped, discarded}`, ids) and `POST /api/sessions/:id/unarchive` (200 `{status, session_id, unarchived}`). The session hub and `GET /api/sessions` keep archived sessions, `archived: true` in their summaries: the page leaves them out of the strip, its count and the list at render, and the `archived` toggle beside the all-sessions search shows them, dimmed with an `archived` badge. The info bar marks a session whose live worker runs an older chi than the newest installed (`worker_version` in its summary): `chi 0.18.1 · Restart`, which asks to confirm and calls `POST /api/sessions/:id/restart` (a refusal's reason shows in a toast); a worker from before restarts shows `chi sessions stop ID` instead. The info bar reads `continue → · archive · stop · delete` (`unarchive` on an archived one; no `continue →` on a link continued already, see *Session chains*; `continue →` is a plain button like `archive`, in the accent on an archived session, where it is the thing to do); archiving the open session stays on it, with an Undo toast.
49
55
 
50
56
  **System 1's saved runs** last as long as sessions: the sweep ages them by day file, and deleting a session purges its runs ([system-one.md](system-one.md)).
51
57
 
52
- **Lazy sweep:** automatic prune runs only while `chi web` runs, at most once per `session.sweep_interval_hours` (default 24): the web's session hub gives it a chance on its periodic full scan, and `GET /api/sessions` does too. No cron, and a terminal-only chi never sweeps. Manual prune is always available.
58
+ **Lazy sweep:** automatic prune runs only while `chi web` runs, at most once per `session.sweep_interval_hours` (default 24): the web's session hub gives it a chance on its periodic full scan, and `GET /api/sessions` does too. It runs on one background thread outside the hub's session list lock, so task stops don't block the list. No cron, and a terminal-only chi never sweeps. Manual prune is always available.
53
59
 
54
60
  <a id="cli"></a>**CLI:**
55
61
 
data/docs/testing.md CHANGED
@@ -284,7 +284,9 @@ run, CI) and too long on a fast one. The contract a new spec follows:
284
284
  twice for it: a second boundary crossed between the reads moves the edge (`ModelProfile.model_warning(now:)`).
285
285
  3. **What a spec starts, it stops and waits for** before teardown: `join!(thread, what)`, `with_task_dir { … }`
286
286
  (spec/support/task_dirs.rb: a tasks' folder of its own, its tasks stopped and their exit-status recorders joined
287
- with `TaskRuntime.quiesce!`), a `stop` that joins (`IdleScheduler#stop`). Never only `Thread#kill`.
287
+ with `TaskRuntime.quiesce!`), a `stop` that joins (`IdleScheduler#stop`), `stop_session_hubs` before removing a
288
+ `Web::SessionHub`'s state dir (spec/support/session_hubs.rb: its retention sweep thread writes there). Never only
289
+ `Thread#kill`.
288
290
  4. **"Nothing happens" is shown by counting passes** (the worker's loop rounds, spec/support/worker_loop_rounds.rb;
289
291
  a class's ticks), not by a pause.
290
292
  5. **A wall-clock bound** only as "not the full N s", with at least 5× headroom measured on the slow (x86) laptop.
@@ -399,6 +401,7 @@ any other file requires it, so a spec file run alone still finds its requires. E
399
401
  | `recording_surface.rb` | `RecordingSurface`: a `TerminalUI::Surface` that records commits and slots instead of drawing |
400
402
  | `remote_backend.rb` | `RemoteBackend`: `SessionAccess::Remote` against chi web's Rack app in this process (no socket, LAN token gate) |
401
403
  | `reply_wait_looks.rb` | `ReplyWaitLooks`: counts a `ReplyWait`'s polls, so a step waits for the looks instead of a delay |
404
+ | `session_hubs.rb` | `stop_session_hubs`: stops every `Web::SessionHub` the example built (joining its sweep thread) before a teardown removes the state dir; a config-level after stops any left over |
402
405
  | `stamps.rb` | *helper*: `next_stamp`, distinct ordered times for the lib's `now:` seams; the pinned history clock |
403
406
  | `task_dirs.rb` | `with_task_dir`: a tasks' folder of its own, every task stopped and its recorders joined after |
404
407
  | `test_kernel.rb` | `TestKernel`: `test_kernel` (a real `KernelLoop` to stub `#run` on; its options are `KernelLoop::Services` fields), `attach_services` (swap some of a kernel's services), `run_context` and `test_client` for Engine specs |