samagotchi 0.194.0 → 0.195.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 (82) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +40 -1
  3. data/docs/bundle-authoring.md +1 -1
  4. data/docs/bundles.md +192 -6
  5. data/docs/cli.md +1 -1
  6. data/docs/configuration.md +25 -4
  7. data/docs/internals/attached-context.md +2 -0
  8. data/docs/internals/bridge.md +4 -0
  9. data/docs/internals/engine.md +13 -1
  10. data/docs/internals/knowledge.md +205 -0
  11. data/docs/internals/pages.md +17 -9
  12. data/docs/internals/panes.md +51 -13
  13. data/docs/internals/peers.md +2 -1
  14. data/docs/memory.md +4 -2
  15. data/docs/pages.md +72 -1
  16. data/docs/peers.md +24 -13
  17. data/docs/plugins.md +59 -3
  18. data/docs/releasing.md +1 -1
  19. data/docs/scheduling.md +4 -0
  20. data/docs/sessions.md +8 -1
  21. data/docs/testing.md +3 -1
  22. data/lib/samagotchi/bundles/claude-peer/manifest.yml +8 -5
  23. data/lib/samagotchi/bundles/claude-peer/plugin.rb +2 -2
  24. data/lib/samagotchi/bundles/codex-peer/manifest.yml +8 -5
  25. data/lib/samagotchi/bundles/codex-peer/plugin.rb +3 -3
  26. data/lib/samagotchi/bundles/coordinator/manifest.yml +7 -4
  27. data/lib/samagotchi/bundles/coordinator/plugin.rb +15 -5
  28. data/lib/samagotchi/bundles/coordinator/skill_coordinator.md +10 -0
  29. data/lib/samagotchi/bundles/dev/manifest.yml +3 -2
  30. data/lib/samagotchi/bundles/knowledge/adapters.rb +205 -0
  31. data/lib/samagotchi/bundles/knowledge/catalog.rb +151 -0
  32. data/lib/samagotchi/bundles/knowledge/chi_adapters.rb +160 -0
  33. data/lib/samagotchi/bundles/knowledge/chunker.rb +55 -0
  34. data/lib/samagotchi/bundles/knowledge/github.rb +246 -0
  35. data/lib/samagotchi/bundles/knowledge/manifest.yml +25 -0
  36. data/lib/samagotchi/bundles/knowledge/plugin.rb +788 -0
  37. data/lib/samagotchi/bundles/knowledge/query.rb +30 -0
  38. data/lib/samagotchi/bundles/knowledge/query_log.rb +55 -0
  39. data/lib/samagotchi/bundles/knowledge/refresh.rb +133 -0
  40. data/lib/samagotchi/bundles/knowledge/store.rb +264 -0
  41. data/lib/samagotchi/bundles/reflect/manifest.yml +17 -0
  42. data/lib/samagotchi/bundles/reflect/scripts/reflect.rb +439 -0
  43. data/lib/samagotchi/bundles/reflect/skill_reflect.md +100 -0
  44. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  45. data/lib/samagotchi/guardrails/review_paths.rb +13 -3
  46. data/lib/samagotchi/guardrails_command.rb +3 -9
  47. data/lib/samagotchi/hook_label.rb +19 -0
  48. data/lib/samagotchi/hook_routes.rb +3 -2
  49. data/lib/samagotchi/page_command.rb +90 -6
  50. data/lib/samagotchi/pages/launch.rb +16 -8
  51. data/lib/samagotchi/pages/runner.rb +7 -2
  52. data/lib/samagotchi/pages/runtime.rb +62 -2
  53. data/lib/samagotchi/pages.rb +4 -0
  54. data/lib/samagotchi/panes/kitty.rb +20 -5
  55. data/lib/samagotchi/panes.rb +81 -12
  56. data/lib/samagotchi/plugin/api.rb +7 -1
  57. data/lib/samagotchi/plugin/attached_context.rb +46 -1
  58. data/lib/samagotchi/plugin/context.rb +24 -7
  59. data/lib/samagotchi/plugin/panes.rb +52 -9
  60. data/lib/samagotchi/plugin/peer_start.rb +60 -35
  61. data/lib/samagotchi/plugin/peers.rb +1 -1
  62. data/lib/samagotchi/plugin/project.rb +63 -0
  63. data/lib/samagotchi/plugin/sessions.rb +36 -1
  64. data/lib/samagotchi/plugin/tool_spec.rb +16 -7
  65. data/lib/samagotchi/session.rb +22 -9
  66. data/lib/samagotchi/session_stats.rb +436 -0
  67. data/lib/samagotchi/session_window.rb +30 -0
  68. data/lib/samagotchi/system_one/approval_choice.rb +22 -0
  69. data/lib/samagotchi/system_one/approval_label.rb +4 -6
  70. data/lib/samagotchi/system_prompt.rb +3 -1
  71. data/lib/samagotchi/terminal_ui/attach_launcher.rb +30 -0
  72. data/lib/samagotchi/testing/boundary.rb +17 -4
  73. data/lib/samagotchi/testing/sessions.rb +11 -3
  74. data/lib/samagotchi/toolkit.rb +11 -4
  75. data/lib/samagotchi/toolkit_report_command.rb +14 -18
  76. data/lib/samagotchi/toolkit_suggest.rb +9 -2
  77. data/lib/samagotchi/tools/registry.rb +43 -18
  78. data/lib/samagotchi/tools/tool_index.rb +6 -2
  79. data/lib/samagotchi/turn_excerpts.rb +298 -0
  80. data/lib/samagotchi/turn_stages/toolkit_suggestion.rb +9 -0
  81. data/lib/samagotchi/version.rb +1 -1
  82. metadata +22 -1
@@ -0,0 +1,205 @@
1
+ # The knowledge bundle: store, catalogs, refresh, adapters
2
+
3
+ The user side is [bundles.md](../bundles.md#the-knowledge-bundle). The code is `lib/samagotchi/bundles/knowledge/`:
4
+ `plugin.rb` (the tools, `/knowledge`, the hooks) and its parts, loaded first in this order: `store.rb` (`Store`),
5
+ `query.rb` (`Query`), `chunker.rb` (`Chunker`), `adapters.rb` (`FolderAdapter`, `MemoriesAdapter`),
6
+ `chi_adapters.rb` (`SessionsAdapter`, `ContextAdapter`), `github.rb` (`GithubAdapter`), `catalog.rb` (`Catalog`),
7
+ `refresh.rb` (`Refresh`), `query_log.rb` (`QueryLog`). It is written only against the plugin API: the core seams it
8
+ needs are `chi.tool(declare:)` ([plugins.md](../plugins.md#declare-which-kits-declare-it); the three seats are in
9
+ [engine.md](engine.md#toolsurface)), `ctx.project`, `ctx.sessions.list` / `present_ids` (`SessionStats.summaries`,
10
+ the listing reflect's counts read too) and `ctx.context.snapshots`.
11
+
12
+ ## The store: the sqlite3 CLI
13
+
14
+ One SQLite file per catalog, `index.db`, through the system `sqlite3` CLI (no gem: nothing to build on a user's
15
+ machine or a pod). Every run is
16
+
17
+ ```
18
+ Open3.capture3(SQLITE, "-init", "/dev/null", "-safe", "-bail", "-nofollow", ["-json",] db, stdin_data: sql)
19
+ ```
20
+
21
+ - **`-init /dev/null`**: with piped stdin the CLI still reads `$XDG_CONFIG_HOME/sqlite3/sqliterc` (and
22
+ `~/.sqliterc`); a user's `.headers on` / `.mode box` would break the `-json` parse.
23
+ - **`-safe`** refuses `.shell`, `.system`, `.output`, `.once`, `.read`, `.import`, `.open`, `ATTACH`, `writefile()`,
24
+ `readfile()`, `edit()`, `.save`, `.backup`, `.cd`. So one catalog per call: no cross-file query.
25
+ - **Values are hex.** The SQL text is constant per operation and goes on stdin, never argv. Every value goes in as
26
+ `cast(x'<hex>' as text)`: a batch is one hex-literal JSON array read with `json_each`, and the FTS5 MATCH string
27
+ (which the bundle builds, `Query`) is hex too. A title like `x'; drop table items; --\n.shell echo PWNED` is stored
28
+ as text. Numbers (`since`, `limit`) are `Integer()`s.
29
+ - **`-nofollow`** refuses a db reached through a symlinked path and can't create one. So the catalog folder is
30
+ `File.realpath`ed (and `ctx.data_dir` once), and the db is made in Ruby first with `CREAT | EXCL | NOFOLLOW`,
31
+ mode 0600 (`-wal` / `-shm` inherit it); folders are 0700. It is made as `index.db.new`, given its schema (WAL,
32
+ checkpointed, its `-wal`/`-shm` removed) and renamed to `index.db`: a search finds no db or a whole one, never an
33
+ empty file (`no such table`) or one switching to WAL.
34
+ - **Searches read-write under `pragma query_only=1`**, not `-readonly`: Apple's `-readonly` fails on a WAL db whose
35
+ `-wal`/`-shm` are gone (another binary, a restore, deleted them). A search never waits on a write transaction
36
+ (WAL). `-json` prints nothing (not `[]`) for no rows.
37
+ - **Every run starts `.timeout 2000`** (`Store::BUSY_MS`; the dot-command, since `pragma busy_timeout` prints a row
38
+ into `-json`). Each run is its own process, so each is often the db's sole connection, and a sole connection takes
39
+ an exclusive lock when it opens (WAL recovery) and closes (the checkpoint) the db. With no busy timeout a search
40
+ meeting that lock answered `database is locked` (CI saw it; a stress loop of searches beside a writer, ~1 in 4).
41
+ The lock lasts a few ms; the timeout waits it out (and a writer, for another's transaction).
42
+ - **The load probe** (`Plugin#probe`, once per worker at plugin load, a few ms) runs the real shapes in `:memory:`:
43
+ an FTS5 table, a hex `json_each` insert, a `snippet()`/`bm25()` select with a hex MATCH. A CLI that fails it gets no
44
+ tools (no dead `:always` tool in every session), one `Log.warn`, and `/knowledge` says why. `needs: [sqlite3]` is
45
+ advisory.
46
+
47
+ ```sql
48
+ create table items(id integer primary key, source text, key text, title text, ptr text, url text, path text,
49
+ updated_at integer, sig text, unique(source, key));
50
+ create table chunk_map(chunk integer primary key, item integer, line integer);
51
+ create virtual table chunks using fts5(title, body, tokenize='porter unicode61'); -- no prefix= (+33 % size)
52
+ create table meta(k text primary key, v text); -- the schema version
53
+ ```
54
+
55
+ A schema version other than `Store::SCHEMA_VERSION` drops the file and builds it again (re-creatable data). Writes
56
+ are `begin immediate` transactions of at most 1.5 MB of JSON each (the 2 s busy timeout), under the catalog's
57
+ `index.lock`.
58
+
59
+ **The query** (`Query`): words with no letter or digit are dropped (`"login" AND "--"` finds nothing; an empty MATCH
60
+ is a syntax error: an empty query is refused), each kept word quoted, the last also a prefix (`"sqli"*`), joined by
61
+ AND; under 3 hits an OR pass fills up, ranked after. Ranking is `bm25(chunks, 5.0, 1.0)` (title, body), ties by the
62
+ newer item; one hit per item.
63
+
64
+ **The chunker** (`Chunker`): at most 1,500 chars on line boundaries, a markdown heading starts a chunk, its title is
65
+ the file's name and the nearest heading; text is scrubbed to valid UTF-8; a NUL in the first 8 KB is binary, skipped.
66
+
67
+ ## Catalogs
68
+
69
+ ```
70
+ $XDG_STATE_HOME/samagotchi/plugins/knowledge/ (ctx.data_dir, realpath'd once; dirs 0700, files 0600)
71
+ projects/<project key>/ catalog.json index.db (+ -wal, -shm) queries.jsonl index.lock sources/<name>.lock
72
+ clones/<owner>__<repo>__<digest>/ (a github source's shallow clone)
73
+ system/ the same, for sessions in no project
74
+ catalogs/<name>/ the same, for named catalogs
75
+ ```
76
+
77
+ - `Catalog.locate`: `catalog: NAME` (`[a-z0-9][a-z0-9-]{0,31}`, not `system` or `projects`) → `catalogs/NAME`; else
78
+ `ctx.project.key` → `projects/<key>` (a key that isn't a safe path segment becomes `p_<sha256 prefix>`); else
79
+ `system/`.
80
+ - `catalog.json` holds the sources (name, kind, location, max_age, why, globs, refreshed_at, last_error, items,
81
+ chunks, skipped counts; a github source's `clone`, a sessions or context source's `project_root`, `listed_at`),
82
+ `removed_defaults`, `seeded` and notes. It is read without a lock and written
83
+ (`AtomicFile.write`, 0600) only under `index.lock`, which every index write takes too.
84
+ - **Defaults**, seeded once at a project or system catalog's first use: `project-docs` (kind folder, the project
85
+ root, `FolderAdapter::DOCS_INCLUDE`, tracked only; only when the root is in a git work tree, else a note) and
86
+ `chi-memories` (the project's and the system memories dirs; the system catalog the system dir only). A named
87
+ catalog has none. A removed default stays removed.
88
+
89
+ ## Refresh: at search time only
90
+
91
+ - **When:** only when `knowledge_search` (or `knowledge_add`, for its source) runs. The stale check reads
92
+ `catalog.json` only (`now - refreshed_at > max_age`): a fresh source costs no walk and no `stat`.
93
+ - **Budget:** the selected stale sources refresh on a thread the search waits for at most `refresh_budget_ms` (1500;
94
+ `knowledge_add` 10 s for its own source), sessions sources last (a first listing reads every session file). A
95
+ `github` source refreshes on a thread of its own the search never waits for (`Refresh.new(background:)`), unless
96
+ it is its own `knowledge_add`. A named catalog's sessions or context source refreshes only from a session in the
97
+ project recorded at its add (`project_root`): `ctx.sessions` / `ctx.context` read the calling session's project. Past it the answer is read from the index as it is, the age line says
98
+ `refreshing now`, and the thread finishes. It is handed `ctx.cancel_controller` (a cancelled turn stops it between
99
+ groups of 200 items) and is **not joined at worker exit**: a killed `sqlite3` child is safe under WAL, and the next
100
+ refresh redoes that batch.
101
+ - **Locks:** `sources/<name>.lock`, `flock` without waiting, per refresh: one held elsewhere (another worker) is
102
+ skipped (`refreshing elsewhere`). `index.lock` exclusive around each write transaction and `catalog.json` write.
103
+ Readers take none.
104
+ - **Diff:** an adapter lists items with a `sig` (a file's `mtime:size`, a blob sha, a session's `updated_at`, a
105
+ snapshot's revision); only items whose sig changed are read and re-chunked, the gone ones deleted by `chunk_map`.
106
+ An adapter with `#gone(old_keys)` lists only what changed (the sessions one, since the source's `listed_at`, the
107
+ start of its last good refresh, less 2 s; dropped when the source is added again, and ignored when the index holds
108
+ no rows for it, so a rebuilt or deleted index lists in full) and says itself which old keys are gone. An adapter with `#chunks(item)`
109
+ makes its own chunks (a session's: `line` = the message index).
110
+ - **Failures** stay on the source (`last_error`, its time) and show in the age line; old rows stay searchable.
111
+ - A participant's search refreshes only the sources it selected (never a chi one).
112
+
113
+ ## Adapters
114
+
115
+ `items → [Item(key, sig, title, ptr, url, path, updated_at)]`, `text(item) → String | nil`, `skipped → counts`.
116
+
117
+ - **`FolderAdapter`**: inside a git work tree its tracked files only (`git -C DIR ls-files -z`, env
118
+ `GitEnv::UNSET`), else a `Find` walk skipping dot folders, `node_modules`, `vendor`, `tmp`. Each file through
119
+ `File.lstat`: a symlink is never followed, a file whose realpath leaves the root is skipped, so is one
120
+ `ctx.project.secret_name?` names (on its path relative to the root: the denylist's name half, `ReviewPaths
121
+ .secret_name?`), one over 1 MiB, past `max_files` (20,000). `knowledge_list` shows the counts, never names. Root
122
+ refusals (`FolderAdapter.refusal`): `/`, the home folder or above, anything under (or holding) `ctx.project.chi_dirs`
123
+ or the memories dirs (chi data goes through kind `chi`, so the participant rule holds), and a root
124
+ `ctx.project.secret_root?` matches (`~/.ssh`). The guardrail votes first through the tool's `targets:` (a folder's
125
+ `{ paths: [location] }`, a read); the adapter re-checks.
126
+ - **`MemoriesAdapter`**: the top-level `.md` files of `ctx.project.memories_dir` and `system_memories_dir` (not
127
+ `index.md`, not `.trash` or other folders), an overlay (`name.<model-key>.md`) under its memory's name. Pointer
128
+ `memory_read NAME scope`.
129
+ - **`GithubAdapter`** (`github.rb`): `GithubAdapter.parse` is the location's only door (D1): `OWNER/REPO[@REF][:SUBPATH]`
130
+ or `https://github.com/OWNER/REPO[/tree/REF[/SUBPATH]]`; `OWNER` `[A-Za-z0-9][A-Za-z0-9-]{0,38}`, `REPO`
131
+ `[A-Za-z0-9._-]{1,100}` and not `.`/`..`, no part starting with `-`, `REF` with no `..`, whitespace or control
132
+ characters and `git check-ref-format --allow-onelevel REF` (argv) passing, `SUBPATH` relative with no `..` segment.
133
+ `REF` is a branch or a tag: it goes to `clone --branch`, which takes no commit sha. The URL form's `/tree/REF/PATH`
134
+ can't tell a branch with a `/` from its path (`feature/x` reads as branch `feature`, path `x`): that one is
135
+ `OWNER/REPO@feature/x:docs`.
136
+ The clone is `clones/<owner>__<repo>__<digest of the location>/` (two refs of one repo, a case-insensitive disk):
137
+ `gh repo clone --no-upstream OWNER/REPO DIR.partial -- --depth 1 --single-branch --no-tags --config <SAFE>…
138
+ [--branch REF]` (gh's parser takes no `--` before its positionals: the validated name and the bundle's folder are
139
+ its only ones), renamed into place. `SAFE` (`GithubAdapter::SAFE`, a `--config` each on the clone, a `-c` each on
140
+ every other git spawn): `core.hooksPath=/dev/null`, `core.fsmonitor=false`, `protocol.allow=never`,
141
+ `protocol.https.allow=always`, `protocol.ssh.allow=always`, `submodule.recurse=false` (no `file://`, `ext::` or
142
+ other transport a repo's config could name; the spec's git wrapper alone adds `protocol.file.allow=always` for
143
+ its `file://` origin). A pull: `git <SAFE> -C DIR -c credential.helper= -c 'credential.helper=!gh auth
144
+ git-credential' fetch --depth 1 --no-tags origin -- REF|HEAD`, then `reset --hard FETCH_HEAD`; a failing one
145
+ clones again. Every spawn: no shell,
146
+ env `GitEnv::UNSET` + `GIT_TERMINAL_PROMPT=0` + `GIT_LFS_SKIP_SMUDGE=1`, its own process group killed after 120 s.
147
+ The listing is `git ls-tree -r -z --full-tree HEAD` (blob shas are the sigs): symlinks (120000) and submodules
148
+ (160000) skipped, then the folder rules on the clone-relative path. Pointer `OWNER/REPO:path:line`, URL
149
+ `https://github.com/OWNER/REPO/blob/<commit>/<path>#L<line>` (a participant's `read` of the clone, under chi's
150
+ state dir, is denied; the URL isn't). `updated_at` is the HEAD commit's time. `knowledge_remove` deletes the clone.
151
+ - **`SessionsAdapter`** (`chi_adapters.rb`): `ctx.sessions.list(changed_since:)` (`SessionStats.summaries` of the
152
+ session's project, or of no project: no test_run or scratch session, archived ones kept), each changed session read
153
+ with `ctx.sessions.read` (the saved file, or a live worker's snapshot): user messages with no kind or `input` and no
154
+ `source`, model messages with no kind; never `tool_response`, a steer, a system note or `thinking`, nor the user
155
+ messages chi writes: a `!cmd` line (`"!(cmd)\n<output>"`, no `turn_id`: `Steer.shell_line?`'s shape, checked in
156
+ the bundle) and `/continue no`'s reason line (an `opening_id`, no `turn_id`). Every message's text and the
157
+ session's title go through `Redact.text(text, Redact::Viewer.new(cwd: nil))` before they are chunked, as
158
+ `TurnExcerpts` and `ObjectivesRecord` do: a key by shape (`sk-…`, `ghp_…`, …) or by name (`token=…`) is stored
159
+ as `[redacted]`, and home as `~`. Chunks of
160
+ ≤ 1,500 chars, `line` = the index of the message a chunk starts at. Pointer `s:<id>`, rendered `knowledge_search
161
+ open: s:<id>#<line>`. `#gone` = the old keys not in `ctx.sessions.present_ids`. A session that can't be read
162
+ (`ctx.sessions.read` raising) keeps the source's `listed_at` at its `updated_at` (`Refresh`: the min of the
163
+ listing's start and each unread item's), so the next listing reads it again. A named catalog's source added again
164
+ from another project (its `project_root` changes) drops its rows first: they are the old project's, which no id
165
+ sweep removes (`present_ids` is every saved session, not one project's). **The id sweep:** every search that
166
+ selects a sessions source deletes the rows of ids no longer in `present_ids` (~2 ms) before the query, and the
167
+ searching session's own rows are excluded in the query (`Store#search(skip:)`: a project catalog is shared, so
168
+ another session indexes yours). Measured here: listing 407 session files 0.2 s; `Session.load` of this project's 171
169
+ sessions 0.3 s (15,556 user/model messages, 1.4 M chars; `ctx.sessions.read` also asks a running worker for its
170
+ snapshot, not measured): a source's first, full listing costs about 0.5 s before the chunking and the index
171
+ writes, which is why sessions refresh last and past the budget finish in the background.
172
+ - **`ContextAdapter`**: `ctx.context.snapshots` (this project's sources and its sessions' own; read-only, never a
173
+ command), one item per source with a text, key `project/<name>` or `session:<id>/<name>`, sig its revision. A hit
174
+ reads `context_read NAME` when this session has that source attached at that scope (`ctx.context.list`), else
175
+ `knowledge_search open: c:<key>#<line>`. Not redacted: it is a fetched outside text, like a folder's or a
176
+ repository's file (secret-named files are skipped, contents kept), and a redaction that joins a private key's
177
+ lines would move the `c:<key>#<line>` pointers off `context_read`'s lines.
178
+ - **`open:`** reads `Store#chunks_of(key, sources:)` (the chunks of that item in the catalog's chi sessions or
179
+ context sources). A long message's pieces share its line, so a pointer past a line's first chunk is
180
+ `#<line>.<part>` (`Store#search` returns each row's `part`); `open:` shows the chunk at the pointer (else the last
181
+ one before it) and the rest of its line's while they fit 4 KB, with the pointers of the chunks before and after. From the index only; an `s:` pointer at a session no longer in `ctx.sessions.present_ids` is refused before its
182
+ rows are read (a session deleted since the last search's sweep). It writes no query-log line (it is logged as a
183
+ follow-up of the search before it).
184
+
185
+ ## Participants
186
+
187
+ `ctx.turn_author` set: `knowledge_search` drops the `chi` sources before the query (a `sources:` of only chi ones is
188
+ refused; the age line says they were left out) and refuses `catalog:` (a named catalog spans projects; the participant
189
+ was invited to one session). `open:` refuses (every pointer it reads is chi data). `knowledge_add` /
190
+ `knowledge_list` / `knowledge_remove` refuse. A participant's `/` line
191
+ is a 403 already, so `/knowledge` is the owner's.
192
+
193
+ ## The query log and the embeddings gate
194
+
195
+ `queries.jsonl` beside the index, 0600, one line per search: `at, session_id, toolkit, model, catalog, query, words,
196
+ sources, since, hits, top (pointers), stale (names), ms, author (owner|participant)`. An `after_tool_call` hook
197
+ appends the **next 3 tool calls of the same turn** after a search, raw: `{after: <the search's at>, tool, arg}`
198
+ (`arg`, at most 200 chars: a plugin tool's `path` / `name` / `url` / `open` / `query` argument; a built-in's
199
+ target, the flattened call's (`Tools::BuiltinCalls.build`) `path`, else its main argument in `content` (`read`'s
200
+ path, `execute`'s command; a `write` logs its file, never its body), never the tool's name; a `knowledge_search
201
+ open:` is a follow-up, a new search is not); a `before_turn` ends the count. At 5 MB the
202
+ file moves to `queries.1.jsonl` (one kept). Nothing is classified in the bundle: an offline script reads it when the
203
+ Build 3 gate (embeddings) is checked: after ≥ 4 weeks and ≥ 100 owner searches, embeddings are planned only if ≥ 10 %
204
+ of searches are re-searched where the second query hit what the first missed, and a hand check finds most of those
205
+ are meaning misses.
@@ -10,9 +10,11 @@ The user side is [pages.md](../pages.md). This is how a run happens and what it
10
10
  | `pages/builder.rb` | `Builder` (the script's `ui`: `text`, `table`, `walk`) and `TableBlock` (columns, formats, key columns, cells, the total) |
11
11
  | `pages/store.rb` | `Store`: read, list, `record_run`, `record_failure`, `locked`, `remove`, `file_id`, `remove_temporary_outputs` |
12
12
  | `pages/runner.rb` | `Runner.run(argv)`: the runner process's whole job |
13
- | `pages/runtime.rb` | `Runtime`, a script's `runtime`: `#schedules` (`ScheduleList`, `Schedule`, `Run`, `Unreadable`) |
13
+ | `pages/runtime.rb` | `Runtime`, a script's `runtime` (`Runtime.new(page:)`, the run's page from `Runner::Collector.new(name)`): `#schedules` (`ScheduleList`, `Schedule`, `Run`, `Unreadable`), `#sessions` (`SessionStats.read`), `#turn_excerpts` (`TurnExcerpts.read`), `#launch_dir` (`Pages::LAUNCH_DIR_KEY`), `#settings` (the bundle's `settings:` keys of `ConfigFile.bundle_settings`) |
14
+ | `session_stats.rb` (core) | `SessionStats.window` (the one listing seat: window, filters, project pick, cap) and `.read` (its counts: `Listing`, `Project`, `SessionCounts`, `TurnCounts`, `FAILURE_KINDS`) |
15
+ | `turn_excerpts.rb` (core) | `TurnExcerpts.read`: given turns' failing calls (`Result`, `Excerpt`, `Call`), redacted and cut, the one text reader |
14
16
  | `pages/bundled.rb` | `Bundled`: the pages installed bundles ship (a manifest's `pages:`), `Page#refusal` |
15
- | `pages/launch.rb` | `Launch.run(name, timeout:, cancelled:)`: the one launch path |
17
+ | `pages/launch.rb` | `Launch.run(name, timeout:, cancelled:, launch_dir:)`: the one launch path; sets `CHI_PAGE_LAUNCH_DIR` (`Pages::LAUNCH_DIR_KEY`, defined in `pages.rb` so the runner never loads this file) |
16
18
  | `page_command.rb` | `chi page run | list | rm` |
17
19
 
18
20
  `pages.rb` requires json, digest, time, `inline_widgets`, `paths` and `atomic_file`, and autoloads its parts. Nothing
@@ -20,9 +22,13 @@ it reaches at load requires the engine, the config, the web, the plugins, `Child
20
22
  loads it alone. `launch.rb` is the only file that needs `ChildEnv` and `ProcessGroup`, and nothing in `pages.rb`
21
23
  requires it. Two parts load more, and only when used: `Runtime#schedules` requires `schedules.rb` (which reaches the
22
24
  config, `SessionManager` and `ProcessGroup`; about 70 ms) when a script calls it, and `Bundled` requires
23
- `installed_bundles.rb` (the config) when a name has no script of the user's. `spec/pages_runtime_spec.rb` pins it: a
24
- real runner process running a user's page that never calls `runtime` has loaded no `runtime.rb`, `schedules.rb` or
25
- `config.rb`.
25
+ `installed_bundles.rb` (the config) when a name has no script of the user's. `Runtime#sessions` requires
26
+ `session_stats.rb` (the session file, analytics, `CardStore`'s constants, `SessionWindow` and so the config: 75
27
+ files, about 20 ms on the Studio) and `Runtime#turn_excerpts` `turn_excerpts.rb` (`SessionPaths`, `AnalyticsFile`,
28
+ `Redact`: about 1 ms). `#launch_dir` loads nothing, and `#settings` loads the config only for a bundle's page (whose
29
+ run has loaded it already through `Bundled`). `spec/pages_runtime_spec.rb` pins it: a real runner process running a
30
+ user's page that never calls `runtime` has loaded no `runtime.rb`, `schedules.rb`, `config.rb`, `session_stats.rb`,
31
+ `turn_excerpts.rb` or `launch.rb`, and one calling `runtime.settings` or `runtime.launch_dir` no `config.rb`.
26
32
 
27
33
  **The resolver.** `Pages.script_path(name)` is the script a name runs: the user's `NAME.rb` when it exists, else the
28
34
  page of that name an installed bundle ships (`Bundled.find`), else the user's path (no such page). Every read and run
@@ -62,8 +68,9 @@ script 152 against 73 preloaded libraries and a stale `PWD`). It costs about 70
62
68
  `ChildEnv.unbundled` (an installed gem's Bundler changes undone),
63
69
  `ChildEnv.unset` (the spawner's guardrails settings and session markers), `Launch.cleared_keys` unset
64
70
  (`CHI_REMOTE`, every `SAMAGOTCHI_WORKER_*` key and the vendor agent markers `AgentCaller::VENDOR_MARKERS`:
65
- `CLAUDECODE`, `CODEX_THREAD_ID`, `AI_AGENT`, read from those constants), `Paths.absolute_xdg`, and `PWD` set to the
66
- pages folder (spawn's `chdir:` doesn't change it). So a run never goes remote, never looks like a worker's child,
71
+ `CLAUDECODE`, `CODEX_THREAD_ID`, `AI_AGENT`, read from those constants, and `CHI_PAGE_LAUNCH_DIR`), then
72
+ `CHI_PAGE_LAUNCH_DIR` set to the caller's `launch_dir:` (`chi page run`'s `Dir.pwd`; a Refresh passes none, so it
73
+ stays unset), `Paths.absolute_xdg`, and `PWD` set to the pages folder (spawn's `chdir:` doesn't change it). So a run never goes remote, never looks like a worker's child,
67
74
  and a script's `chi send` is the owner's even from a chi web started in an agent's pane. "This chi's lib" is
68
75
  `File.expand_path("../..", __dir__)` from `pages/launch.rb`: a checkout and an installed gem alike.
69
76
  3. stdout and stderr are each read by a `ProcessGroup::PipeReader` (64 KB, the tail kept).
@@ -216,7 +223,8 @@ owner's `~/.claude/plans/evals/0016-pages-skill/`.
216
223
 
217
224
  ## Later builds
218
225
 
219
- - `runtime` has one method, `schedules`, with its first page (the schedules bundle). A method comes with its first
220
- caller: sessions, a session's stats, a config value are the candidates.
226
+ - `runtime` has `schedules` (its first page: the schedules bundle), and, experimental, `sessions`, `turn_excerpts`,
227
+ `launch_dir` and `settings` (their first page: the reflect bundle). A method comes with its first caller.
228
+ `launch_dir` is not a page parameter: it is only where the run was typed.
221
229
  - Not planned yet: picks on a page, parameters, a live install (the hub watches the pages folder only, so a bundle's
222
230
  page shows on the next list read).
@@ -1,9 +1,9 @@
1
1
  # Panes: the windows agents run in
2
2
 
3
3
  A pane is where an agent's own UI runs and where the human can walk in: today a kitty window. It carries no peer
4
- message (that is the mailbox, [peers.md](peers.md)). `list`, `find` and `show` find and raise a window; `open`,
5
- `alive?` and `paste` open a background tab and type into it (claude-peer's and codex-peer's `/<peer> start`,
6
- `Plugin::PeerStart`).
4
+ message (that is the mailbox, [peers.md](peers.md)). `list`, `find`, `find_var` and `show` find and raise a window;
5
+ `open`, `alive?` and `paste` open a window (a background tab, or one next to the session's chi terminal) and type
6
+ into it (claude-peer's and codex-peer's `/<peer> start`, `Plugin::PeerStart`).
7
7
 
8
8
  `Samagotchi::Panes` (`lib/samagotchi/panes.rb`), the pure parts in `Panes::Kitty` (`panes/kitty.rb`), ported from the
9
9
  desktop helper's `Kitty.swift` as they are:
@@ -18,7 +18,21 @@ desktop helper's `Kitty.swift` as they are:
18
18
  - **Finding a window:** the one whose `foreground_processes[].pid` contains the pid (membership: never
19
19
  `windows[].pid`, which is the login wrapper or a launcher's sh). Its title is `windows[].title` (never the tab's:
20
20
  a tab holds several windows), cleaned as the helper's `AgentText.cleanTitle` (the status glyph dropped).
21
- - **Show:** `focus-window --match id:N` on its socket: it brings a background tab forward, and a background OS
21
+ - **What `ls` gives a `Pane`:** besides the key, title, cwd and pids, the window's `user_vars` (`vars`) and its tab's
22
+ `layout` (`tab_layout`: `fat`, `splits`, `stack`…; "" when `ls` has none) and `is_focused` (`tab_focused`: the
23
+ active tab of the focused OS window). kitty 0.49.2's `ls` has all of them (`Window.as_dict`, `TabManager.list_tabs`).
24
+ - **The session's terminal (the mark):** the attached TUI (`TerminalUI::AttachLauncher#mark_window`) sets the user var
25
+ `chi_session` (`Panes::SESSION_VAR`) on its own window to `<session id>:<its pid>` (`Panes.session_mark`) with the
26
+ OSC 1337 `SetUserVar` escape (`Kitty.user_var`: the value base64, as kitty requires), written before the live
27
+ region opens and unset (the no-`=` form; an empty value would leave `""`) after it closes, in `run`'s outer
28
+ `ensure`, so every way out but kill -9 clears it. Only with `KITTY_WINDOW_ID` set and stdout a tty (a piped
29
+ `chi -p … | tee` never gets it), never for a `--remote` attach. No socket is needed (an escape, not
30
+ `kitty @ set-user-vars`). Inside tmux the escape is dropped unless tmux passes it through: no mark, so a start
31
+ opens a tab. `spec_helper` drops `KITTY_WINDOW_ID`, so a suite run in kitty marks nothing.
32
+ - **Finding the mark:** `find_var(name, id)` is the window whose var `name` matches `\A<id>:(\d+)\z` (the id
33
+ escaped) while that pid is among its foreground pids: a TUI killed hard leaves its mark on a window that may run a
34
+ shell now, and that one never matches. Several (two attached terminals of one session): the focused tab's first,
35
+ else the first in `ls` order. on its socket: it brings a background tab forward, and a background OS
22
36
  window (checked with `kitty @ ls`'s `is_focused` while the screen was unlocked).
23
37
  - **Open:** `open(command:, cwd:, title:)` runs `launch --type=tab --keep-focus --cwd DIR --tab-title TITLE ARGV…`
24
38
  on the kitty whose OS window is focused (`ls`'s `is_focused`), else the live socket file with the newest mtime (the
@@ -27,6 +41,15 @@ desktop helper's `Kitty.swift` as they are:
27
41
  15 s limit (`LAUNCH_SECONDS`; `ls` 2 s, the rest 5 s): one killed early may still open a tab no ref names. No socket answering
28
42
  raises `Panes::Unavailable`, the one message "kitty isn't running or `kitty.listen_on` isn't set"; a launch that
29
43
  fails or prints no id raises `Panes::Error`.
44
+ - **Open next to a window:** `open(…, next_to: pane)` runs, on **that pane's own socket** (checked as any ref is),
45
+ `launch --type=window --match window_id:N --next-to id:N --location=LOC --keep-focus --cwd DIR ARGV…`. The
46
+ `--match window_id:N` picks the pane's tab: over remote control kitty ignores `--next-to` unless the matched window
47
+ is in the target tab, the active one by default, so without it the window would land in whatever tab the user is
48
+ in (`window_id:`, not `id:`, which for `launch` first looks for a tab id). `LOC` is `split` in the `splits` layout,
49
+ else `neighbor` (the slot after it: in `fat`, the default layout, a strip under chi). No `--title` (it would freeze
50
+ the title the command sets, which Show's lists read). A non-zero exit (the window gone since the `ls`, a kitty that
51
+ refuses `--next-to`, anything: stderr isn't read) raises `Panes::SplitFailed`; a timeout raises `Panes::Error`,
52
+ never `SplitFailed`, since a slow launch may still open its window (`run` tells `:timeout` from `:failed`).
30
53
  - **Alive and paste:** `alive?(ref)` is `ls --match id:N` on the ref's socket. `paste(ref, text, enter:)` is the
31
54
  helper's `KittyRunner#send`: `alive?` first (send-text reports nothing for a gone window), then
32
55
  `send-text --match id:N --bracketed-paste=disable --stdin` with the text wrapped in `ESC[200~ … ESC[201~` (its own
@@ -38,8 +61,8 @@ desktop helper's `Kitty.swift` as they are:
38
61
  - **No kitty** (unset, not running, the pid in no window, the binary missing): nothing found, no error; a row then
39
62
  has no Show.
40
63
 
41
- `ctx.panes` (`Plugin::Panes`, [plugins.md](../plugins.md)) is the plugin's view: `find(pid:)`, `alive?(ref)`, and
42
- `show`, `open` and `paste`, which raise `Plugin::Panes::NotTyped` unless the command was typed or tapped by a person
64
+ `ctx.panes` (`Plugin::Panes`, [plugins.md](../plugins.md)) is the plugin's view, built with its session's id:
65
+ `find(pid:)`, `alive?(ref)`, and `show`, `open` and `paste`, which raise `Plugin::Panes::NotTyped` unless the command was typed or tapped by a person
43
66
  (`ctx.user_typed?`, `UserTyped`): they act as the user on their screen, so no tool call, `chi send`, agent, participant, schedule, delegate or plugin path reaches them. The seam trusts the request's client id, so it is an accident guard as the guardrails are ([guardrails.md](../guardrails.md#protected-paths)), not a sandbox: a model's shell holding the Bridge's secret could still post as a UI, as it can a `!` line. Nothing derived from `.here` is used to open or
44
67
  paste: `/<peer> start` keeps its `PaneRef` in the bundle's own session state (`state.json` under `ctx.session_dir`, a
45
68
  `SessionStores` row removed with the session), never in the mailbox. That file is not protected (chi's own tools can
@@ -48,19 +71,34 @@ one of `kitty.listen_on`'s own (`Kitty.sockets`), else they answer as for a clos
48
71
  session's `/<peer> show` also needs the paired peer's pid in that window. A continue doesn't carry that state (the
49
72
  pairing it does).
50
73
 
74
+ `Plugin::Panes#open(command:, cwd:, title:, in: :tab)` (another `in:`, a string too, is an `ArgumentError`): `:tab` is the background tab; `:pane` is `find_var` of this
75
+ session's mark, then a window next to it, else a tab: no mark, the mark's tab in the `stack` layout (the window
76
+ would open hidden behind chi, `--keep-focus`), or a `SplitFailed` (one tab launch then; a timeout gets none and
77
+ raises as any open error). A block gets a `Plugin::Panes::Placed(kind, why)`: `:pane`, or `:tab` with the reason
78
+ (`NO_TERMINAL`, `STACKED`, `SPLIT_FAILED`) when a pane was asked for. Either way it returns the `PaneRef`, so
79
+ `alive?`, `show`, `paste` and the saved record work the same for a pane and a tab (all per window). A start tapped
80
+ in chi web or on the phone opens next to the session's attached TUI too when there is one: the rule names the
81
+ session's terminal, not where the tap came from. One extra `ls` per start (`find_var`; the tab path has its own).
82
+
51
83
  `/<peer> start` (`Plugin::PeerStart`): the checks (typed, no live pairing, claude-peer's start hook current), then
52
84
  the wait (`ctx.peers.wait`), then `open` with `[$SHELL, -l, -c, "exec <start_command>"]` (the account's shell when
53
- `$SHELL` is unset). An open wait (`/<peer> pair`'s) is kept, not rewritten; a pane error takes back only the wait
85
+ `$SHELL` is unset) and `in:` from the bundle setting `open_in` (`pane`, the default, or `tab`; another value means
86
+ `pane`, and the start line names it: no setting checks values, only keys and types). The start line says what
87
+ opened ("opened a pane next to this chi", or "opened a background tab "<title>" (why)"); every later line says
88
+ "kitty window" for both, so the saved record needs no kind. An open wait (`/<peer> pair`'s) is kept, not rewritten; a pane error takes back only the wait
54
89
  this start wrote (`ctx.peers.stop_waiting(name, mark)`, `PeerPresence.drop_wait`: never another wait nor an announce's
55
- claimed file), so a refusal leaves no mark of its own. A second start while the wait is open and its tab `alive?` (a
56
- double tap) is refused, "already starting in kitty tab …"; two at the same moment take turns on a flock
57
- (`start.lock` in `ctx.session_dir`, held across the checks, the wait and the open: commands run in parallel). The tab
90
+ claimed file), so a refusal leaves no mark of its own. A second start while the wait is open and its window `alive?` (a
91
+ double tap) is refused, "already starting claude · chi <id8> in kitty …" (chi's label, the saved `title`: a
92
+ pane carries no title of chi's); two at the same moment take turns on a flock
93
+ (`start.lock` in `ctx.session_dir`, held across the checks, the wait and the open: commands run in parallel). The window
58
94
  is checked once more 1.5 s after the launch (`PeerStart.settle_seconds`): gone already (its command not found), the
59
95
  start's wait is taken back and the reply names `start_command`. The
60
96
  status card's started row (scene 5) shows while the ref is `alive?` and the paired Claude's pid (its `PeerHere`) runs
61
- in that window, and "its kitty tab is closed" once the ref is gone and so is the pairing's socket.
97
+ in that window, and "its kitty window is closed" once the ref is gone and so is the pairing's socket.
62
98
 
63
99
  Specs: `spec/panes_spec.rb` (on `spec/fixtures/desktop/fake_kitty`, which answers `ls`, `launch`, `focus-window`,
64
- `send-text` and `send-key`, and logs the argv, stdin and `KITTY_*` env it got; its canned windows carry pids, its OS
65
- windows `is_focused`) and `spec/samagotchi/bundles/claude_peer_start_spec.rb`. No spec reaches a running kitty
100
+ `send-text` and `send-key`, and logs the argv, stdin and `KITTY_*` env it got; its canned windows carry pids and
101
+ `user_vars`, its tabs `layout` and `is_focused`, its OS windows `is_focused`; `launch --match window_id:N` adds the
102
+ window to N's tab or exits 1, and `$FAKE_KITTY_SPLIT_FAILS` / `$FAKE_KITTY_LAUNCH_SLEEP` play a kitty that refuses
103
+ `--next-to` and a slow launch), `spec/terminal_ui/attach_launcher_spec.rb` (the mark) and `spec/samagotchi/bundles/claude_peer_start_spec.rb`. No spec reaches a running kitty
66
104
  ([testing.md](../testing.md)).
@@ -126,7 +126,8 @@ live by its pid, `ctx.panes`, only under `ctx.user_typed?`), `unpair`. A bundle
126
126
  Codex's hooks.json (the bundle's `#hook_file`, `#start_hook_line`, `#hook_paragraph`, `#hook_written_line`,
127
127
  `#hook_stale_tail`); `#with_hook` replaces an announce line in place, else appends a group, never reorders (Codex's
128
128
  trust is `[hooks.state."<file>:session_start:<group>:<hook>"]` in config.toml, index-keyed, which chi never writes). `/<peer> start`
129
- (`Plugin::PeerStart`) writes the wait and opens a kitty tab running the peer: it has no path of its own to pair (the
129
+ (`Plugin::PeerStart`) writes the wait and opens a kitty window running the peer (a pane next to the session's chi terminal, or a
130
+ background tab: the bundle setting `open_in`, [panes.md](panes.md)): it has no path of its own to pair (the
130
131
  started Claude's announce takes the wait; codex-peer's first prompt runs the skill's `--here`, or its start hook
131
132
  takes the wait at that prompt; `#start_needs_hook?`: claude true, codex false, and codex's opened line adds
132
133
  `#start_review_hint` while its hook is current); its `PaneRef` lives
data/docs/memory.md CHANGED
@@ -446,7 +446,9 @@ chi ships one skill itself: `skill_pages` in the system bundle
446
446
  page ([docs/pages.md](pages.md#asking-chi-for-a-page)). Its index line is in
447
447
  every prompt; its text is read only when a page is asked for. It tells chi not
448
448
  to edit it (a shipped file: a local edit would have to be merged at the next
449
- upgrade) but to say what differed.
449
+ upgrade) but to say what differed. The opt-in reflect bundle ships a second,
450
+ `skill_reflect`: a nightly reflect session's steps, which suggest changes and
451
+ never apply them ([docs/bundles.md](bundles.md#a-nightly-reflect-session)).
450
452
 
451
453
  ## Toolkit memories
452
454
 
@@ -666,7 +668,7 @@ profiles, meta bundles that install a set of them:
666
668
  | profile | bundles |
667
669
  |---|---|
668
670
  | `core` | loop-guard, check-in, guardrails, slow-commands, agents-md, cost-cap, work-cap: the recommended safety set |
669
- | `dev` | known-names, mcp, btw, skills, source-links, github-pr, coordinator, claude-peer, codex-peer, ruby, model-notes |
671
+ | `dev` | known-names, mcp, btw, skills, source-links, github-pr, coordinator, claude-peer, codex-peer, ruby, model-notes, decision-card, inline-widgets, knowledge |
670
672
 
671
673
  `chi bootstrap` installs `core` and, on a terminal, offers `dev`. An existing
672
674
  install gets neither by itself: `chi bundle install core` (or `dev`).
data/docs/pages.md CHANGED
@@ -99,7 +99,68 @@ it. On an older chi `runtime` is a `NameError`, and the run fails with it (the l
99
99
  remove it before changing schedules`). The read takes no lock and writes nothing, though chi's debug log may get a
100
100
  line for an entry that doesn't read.
101
101
 
102
- `runtime`, like the rest of the page script DSL, is stable for bundles ([plugins.md](plugins.md#stable-for-bundles)).
102
+ The next four are **experimental** (from the chi after 0.194.0): their members may change while the first page that
103
+ uses them (the reflect bundle's) settles.
104
+
105
+ - **`runtime.sessions(project: nil)`**: one project's sessions over the last 14 days, as counts (a
106
+ `SessionStats::Listing`). Read-only and local: it reads the session files, `analytics.json` and `cards.json`, takes
107
+ no lock and starts no worker.
108
+ - **Which project.** `project:` is a folder: its project is read (a worktree gives its repository, a
109
+ `chi project init` folder its marked folder), even with no session in the window (then `session_count` 0 and no
110
+ sessions). nil, or a folder in no project: the project of the newest session **you started** (not a delegate,
111
+ and started by no agent, schedule or participant; a web tab's, a TUI's, `chi send`'s and a continued link's
112
+ count as yours), else the newest session's. `runtime.sessions(project: runtime.launch_dir)` reads the project
113
+ `chi page run` was typed in.
114
+ - **The listing.** `project` (`name`, `path` with `~` for your home, `session_count`; nil only when no project is
115
+ picked: no `project:` folder in a project and no session in the window), `picked_by` (`"folder"` or `"newest"`),
116
+ `projects` (every other project in the window, most sessions first), `sessions` (newest updated first), `since` (the
117
+ window's start, ISO 8601 UTC), `sessions_capped` (true when more than 500 of the project's sessions matched: the cap
118
+ counts after the project filter, and is lower when `session.max_count` is), `unreadable` (files that didn't read;
119
+ their counts are 0). The 14 days are capped by `session.retention_days`. `test_run` and `scratch` sessions are left
120
+ out; archived ones and delegates count.
121
+ - **A session** (`SessionCounts`): `id`, `created_at`, `updated_at`, `model_name`, `delegate`, `chain_link`,
122
+ `turns`, `tool_calls_by_tool` and `tool_errors_by_tool` (tool → n), `blocked` (every guardrail deny: a rule, a
123
+ hook, you or a parent declining, a tool not in the toolkit), `auto_allowed` (System 1's), `mid_turn_lines` (your
124
+ own lines into a running turn), `steers_by_source` (plugins' steers), `approvals_by_rule` (rule →
125
+ `{"asked", "once", "wide", "denied", "unanswered", "by_parent"}`; a question with no rule under `(no rule)`),
126
+ `cards_at_cap` and `hook_notices_by_bundle` / `notices_at_cap` (see "at least" below), `context_window`,
127
+ `side_cost` (recaps, `/btw`, `ask_model`: a session total, not windowed) and `schedule_id` (the schedule whose
128
+ chain link it is, else nil).
129
+ - **A turn** (`TurnCounts`): `id`, `started_at`, `status` (`completed`, `failed`, `canceled`), `cancel` (`you`: your
130
+ Stop or Ctrl-C, a participant's cancel included; `hook`; `interrupted`: the worker went mid-turn, never a
131
+ cancel; `other`; nil when not cancelled), `cancel_bundle` (the hook's bundle), `automatic` (started by no
132
+ person: a schedule, a delegate report, a reminder), `model` (for a failed turn, its model ref without the host),
133
+ `cost` (reported plus estimated), `tool_calls`, `tool_errors`, `tool_calls_by_tool`, `tool_errors_by_tool`,
134
+ `failure_kind` (one of `host_model_not_found`, `host_rejected`, `host_error`, `timeout`, `host_unreachable`,
135
+ `context_overflow`, `empty_answer`, `other`, `none`; nil unless failed) and `context_used_tokens`.
136
+ - **The window.** Turns count by when they started; tool records, approvals and notices by their turn; your lines
137
+ and steers by their own time; a question with no turn id by when it was asked. Anything with neither is left out.
138
+ - **No text.** Counts, ids, times, model names, the project's name and path, and the names the Hashes are keyed by
139
+ (tools, rules, bundles, steer sources): never a message, a title, a tool's output or command, or a failure's
140
+ words (only its kind).
141
+ - **"At least".** `cards.json` keeps the last 20 questions and cards, and the last 20 notices: `cards_at_cap` /
142
+ `notices_at_cap` say a session's approvals / hook notices may be more. An approval a participant's turn asked
143
+ counts with yours.
144
+ - A running turn reads as its last save: missing, or `interrupted` after a checkpoint.
145
+ - **`runtime.turn_excerpts(turns, include_text: false)`**: for each `[session_id, turn_id]` (worst first, as
146
+ `runtime.sessions` gives them), the turn's failing tool calls with their error results: **text from your
147
+ sessions**, which reaches whatever reads the page. A `TurnExcerpts::Result`: `excerpts`, `left_out` (calls the cap
148
+ dropped), `unpaired`, `unreadable`. An excerpt has `session_id`, `turn_id`, `started_at`, `status`, `failure` (a
149
+ failed turn's line), `calls` (at most 8: `tool`, `target` for a `call_tool`'s `<server>/<tool>`, `status` `error`
150
+ or `blocked`, `args` cut at 200 characters, `result` cut at 300), `paired`, and `prompt` / `answer` (the turn's
151
+ opening message and last answer, cut at 300; nil unless `include_text: true`). Every field has key shapes
152
+ redacted and your home as `~`, and all of them together stay within about 4k tokens (14,000 characters), filled
153
+ in the order given. A turn whose calls can't be matched to its messages exactly (a continue turn, a raw-prompt
154
+ batch) is `paired: false`: its calls with tool and status only, never a guess.
155
+ - **`runtime.launch_dir`**: the folder `chi page run` was typed in, an absolute path; nil when chi web's Refresh ran
156
+ the page, or when the folder is gone. The run itself still happens in the pages folder
157
+ ([Where a run happens](#where-a-run-happens)).
158
+ - **`runtime.settings`**: a bundle page's own settings: the keys its manifest lists in `settings:`, from config.yml
159
+ `bundles: <bundle>:`, as written (the page checks their types). `{}` for your own page, for a bundle with no
160
+ `settings:`, and when config.yml has none.
161
+
162
+ `runtime`, like the rest of the page script DSL, is stable for bundles (except the experimental ones above;
163
+ [plugins.md](plugins.md#stable-for-bundles)).
103
164
 
104
165
  ## Pages from a bundle
105
166
 
@@ -126,6 +187,14 @@ A bundle can ship pages: its manifest's `pages:` names scripts in its `scripts/`
126
187
 
127
188
  - `chi page run NAME` runs the script in a Ruby process of its own and prints a summary of each block: a text's first
128
189
  lines, a table's labels, first rows and total, a walk's step count. `--format json` prints the stored page.
190
+ `--format lines` prints the stored page in full, uncut: the name and title, `ran_at:` (and `error:` after a failed
191
+ run, which exits 1 as json does, followed by the last lines of the script's stderr, indented), then `== block N:
192
+ TYPE` before each block, a text's lines as they are, a table's labels and one row a line (cells formatted as in the
193
+ summary, `|` between, a newline in a cell as a space) and its total, a walk's title and one step a line. In a cell a
194
+ `\` prints as `\\` and a `|` as `\|` (`grep x | head` is `grep x \| head`), so a cell never reads as two; a block's
195
+ line that starts with `== block ` gets a `\` before it, so no block forges another's header. It is the form a model
196
+ reads in parts: one JSON line is cut at a tool result's limit, while `execute` saves long output whole and names the
197
+ file to `read` by `start_line`.
129
198
  - A run that fails (the script raised, has a syntax error, called `exit`, broke a limit, or printed more than 256 KB of
130
199
  blocks) prints `error: line 9: undefined method 'fetch' for nil`, the last lines of what the script wrote to stderr,
131
200
  and exits 1. **The result of the last good run is kept**: a bad edit never blanks the page.
@@ -184,6 +253,8 @@ that breaks the rule). See [the CLI](cli.md#commands).
184
253
  - **The working folder is the pages folder.** A chi command a script runs sees that folder's project: if
185
254
  `~/.config` sits in a git repository, that repository. Pass `--scope=all` to the session commands
186
255
  (`chi sessions list --scope=all --format json`) for every project.
256
+ The folder `chi page run` was typed in reaches the script only as `runtime.launch_dir` (`CHI_PAGE_LAUNCH_DIR`;
257
+ never set from a Refresh, nor inherited).
187
258
  - **The environment is yours**, as a session's worker gets it: the XDG folders absolute, chi's own session markers and
188
259
  guardrails settings left out, and `PWD` the pages folder; chi web's Refresh runs chi web's own chi. `CHI_REMOTE`, a worker's `SAMAGOTCHI_WORKER_*` keys and
189
260
  the agent markers (`CLAUDECODE`, `CODEX_THREAD_ID`, `AI_AGENT`) are left out too: a run is always on this machine,
data/docs/peers.md CHANGED
@@ -64,7 +64,7 @@ shown).
64
64
  - **Review it in Codex.** Codex asks you to review a new or changed hook the next time it starts ("Hooks need
65
65
  review": choose Review hooks, or `/hooks` later, and trust it); until then it skips the hook, silently. chi never
66
66
  writes Codex's trust and never passes a trust-bypass flag. A Codex started by `/codex start` stops on that screen
67
- in its background tab the first time: its opened line says so; Show the tab and answer it.
67
+ in its kitty window the first time: its opened line says so; Show the window and answer it.
68
68
  - A line pointing at a chi that is gone (a moved chi home) shows on the status card; adding it again changes the hook,
69
69
  so Codex asks for the review again.
70
70
  - Codex runs an interactive session's hooks in its app-server daemon, with the env of the Codex that started the
@@ -72,21 +72,32 @@ shown).
72
72
  nothing shows). The card reads only `$CODEX_HOME/hooks.json`: an announce line you put in `config.toml`'s `[hooks]`
73
73
  or a project's `.codex/hooks.json` isn't seen (the card offers to add it).
74
74
 
75
- **Start one in kitty: `/claude start`.** chi makes the session wait, then opens a background kitty tab titled
76
- `claude · chi <id8>` in the session's folder, running `claude` through your login shell (the setting
77
- `bundles: claude-peer: start_command:` replaces it, a shell line, so you can add flags; read when the session's worker
78
- starts, as every bundle setting is, so restart the session after changing it); the Claude there pairs on its
79
- own when it starts, through the start hook. The tab opens in the kitty whose window has the focus, else the one
80
- started last, and never takes the focus. `/claude` then says **Paired · started by chi** with the tab's title and
81
- **Show** (`/claude show`, which brings the tab to the front); once the tab is closed it says so, with **Start one in
82
- kitty**. It needs kitty with remote control (`kitty.listen_on`, [configuration.md](configuration.md#desktop-helper-agents-in-kitty-and-tmux)):
75
+ **Start one in kitty: `/claude start`.** chi makes the session wait, then opens a kitty window in the session's
76
+ folder, running `claude` through your login shell (the setting `bundles: claude-peer: start_command:` replaces it, a
77
+ shell line, so you can add flags; read when the session's worker starts, as every bundle setting is, so restart the
78
+ session after changing it); the Claude there pairs on its own when it starts, through the start hook. Where it opens:
79
+
80
+ - **A pane next to this chi** (the default): when this session's chi terminal runs in kitty, Claude opens in that
81
+ terminal's tab, beside it, whichever tab you are in now: a split in kitty's `splits` layout, the layout's next slot
82
+ in the others (in `fat`, kitty's default, a strip under chi). The start line says "opened a pane next to this chi".
83
+ The same from chi web or the phone, while the session's terminal is attached.
84
+ - **A background tab** titled `claude · chi <id8>` otherwise, and the start line says why: no chi terminal of this
85
+ session in kitty (a start from chi web with no terminal attached, a chi terminal in another app or inside tmux), its
86
+ tab in the `stack` layout (the pane would hide behind chi), or kitty refusing the pane. The tab opens in the kitty
87
+ whose window has the focus, else the one started last. `bundles: claude-peer: open_in: tab` always opens the tab
88
+ (`open_in: pane` is the default; another value is taken as `pane`, and the start line says so).
89
+
90
+ Neither takes the focus. With two chi terminals of the session in kitty, the one in the focused tab wins. `/claude`
91
+ then says **Paired · started by chi** with chi's label for it, `claude · chi <id8>` (a pane carries no title of
92
+ chi's; only the tab is titled so), and **Show** (`/claude show`, which brings the window to
93
+ the front); once the window is closed it says so, with **Start one in kitty**. It needs kitty with remote control (`kitty.listen_on`, [configuration.md](configuration.md#desktop-helper-agents-in-kitty-and-tmux)):
83
94
  without it, "kitty isn't running or `kitty.listen_on` isn't set", and nothing waits. It refuses on a session already
84
95
  paired, and without the start hook ("install the start hook first"). From the phone it works the same while kitty runs
85
96
  on the working machine. `/codex start` opens Codex the same way (`bundles: codex-peer: start_command:`, default
86
- `codex`) with the first prompt "pair with chi", which runs the skill's pair and so spends one Codex turn; it needs no
87
- hook (with Codex's start hook, the hook pairs at that first message and the skill's pair says paired). Start, Show and pasting into a tab run only from your typing or tap: no tool call, `chi send`, agent, participant,
88
- schedule or delegate reaches them. A second Start while the first tab is still starting is refused, two at the same
89
- moment included (they take turns). A tab that closes at once (its command isn't found in the login shell's PATH: it
97
+ `codex`, and `open_in`) with the first prompt "pair with chi", which runs the skill's pair and so spends one Codex turn; it needs no
98
+ hook (with Codex's start hook, the hook pairs at that first message and the skill's pair says paired). Start, Show and pasting into a window run only from your typing or tap: no tool call, `chi send`, agent, participant,
99
+ schedule or delegate reaches them. A second Start while the first window is still starting is refused, two at the same
100
+ moment included (they take turns). A window that closes at once (its command isn't found in the login shell's PATH: it
90
101
  runs as `$SHELL -l -c "exec <start_command>"`) is said so, and leaves no wait; after its Claude ended, the status card's
91
102
  title reads `claude-peer: ended` and the chip `Claude · ended`.
92
103