scout-ai 2.1.0 → 2.2.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 (186) hide show
  1. checksums.yaml +4 -4
  2. data/.vimproject +133 -58
  3. data/README.md +2 -1
  4. data/VERSION +1 -1
  5. data/doc/Improvements.md +490 -148
  6. data/doc/Model.md +53 -10
  7. data/doc/StartHere.md +44 -19
  8. data/doc/developer/Architecture.md +25 -6
  9. data/doc/developer/Backends.md +207 -48
  10. data/doc/developer/ChatLifecycle.md +121 -20
  11. data/doc/developer/DelegationInternals.md +319 -33
  12. data/doc/developer/DesignPrinciples.md +205 -16
  13. data/doc/developer/PathEngine.md +628 -0
  14. data/doc/developer/PromptProcessing.md +332 -82
  15. data/doc/developer/Provenance.md +388 -40
  16. data/doc/developer/Sandbox.md +213 -0
  17. data/doc/user/BuildingAgents.md +130 -18
  18. data/doc/user/Cookbook.md +29 -8
  19. data/doc/user/CoreConcepts.md +7 -6
  20. data/doc/user/Delegation.md +166 -15
  21. data/doc/user/GettingStarted.md +20 -16
  22. data/doc/user/ManagingContext.md +155 -17
  23. data/doc/user/MultiAgentWorkflows.md +105 -15
  24. data/doc/user/Python.md +11 -1
  25. data/doc/user/RunningInference.md +90 -47
  26. data/doc/user/ToolCalling.md +134 -29
  27. data/doc/user/WritingChats.md +56 -27
  28. data/lib/scout/llm/agent/attach.rb +13 -17
  29. data/lib/scout/llm/agent/chat.rb +32 -0
  30. data/lib/scout/llm/agent/construction.rb +64 -0
  31. data/lib/scout/llm/agent/conversation.rb +304 -0
  32. data/lib/scout/llm/agent/delegate.rb +56 -238
  33. data/lib/scout/llm/agent/path/edit.rb +230 -0
  34. data/lib/scout/llm/agent/path/patch.rb +252 -0
  35. data/lib/scout/llm/agent/path/workflow_kinds.rb +175 -0
  36. data/lib/scout/llm/agent/path.rb +1777 -0
  37. data/lib/scout/llm/agent/save.rb +11 -9
  38. data/lib/scout/llm/agent/workflow.rb +77 -16
  39. data/lib/scout/llm/agent.rb +147 -31
  40. data/lib/scout/llm/ask.rb +28 -17
  41. data/lib/scout/llm/backends/anthropic.rb +1 -1
  42. data/lib/scout/llm/backends/bedrock.rb +3 -2
  43. data/lib/scout/llm/backends/default.rb +127 -34
  44. data/lib/scout/llm/backends/glm.rb +28 -1
  45. data/lib/scout/llm/backends/huggingface.rb +1 -1
  46. data/lib/scout/llm/backends/ollama.rb +1 -1
  47. data/lib/scout/llm/backends/openai.rb +7 -6
  48. data/lib/scout/llm/backends/openwebui.rb +14 -7
  49. data/lib/scout/llm/backends/relay.rb +8 -2
  50. data/lib/scout/llm/chat/agent_meta.rb +24 -60
  51. data/lib/scout/llm/chat/parse.rb +1 -1
  52. data/lib/scout/llm/chat/process/files.rb +10 -0
  53. data/lib/scout/llm/chat/process/meta.rb +5 -7
  54. data/lib/scout/llm/chat/process/tools.rb +104 -49
  55. data/lib/scout/llm/chat/prompt/epoch_tool_compactation.rb +355 -0
  56. data/lib/scout/llm/chat/prompt/inbox.rb +188 -0
  57. data/lib/scout/llm/chat/prompt/shorten_tools.rb +797 -13
  58. data/lib/scout/llm/chat/prompt/shorten_tools_epoch.rb +1 -365
  59. data/lib/scout/llm/chat/prompt/shorten_tools_epoch_increment.rb +1 -0
  60. data/lib/scout/llm/chat/prompt.rb +24 -10
  61. data/lib/scout/llm/chat/provenance/live.rb +1080 -0
  62. data/lib/scout/llm/chat/provenance/tokens.rb +386 -0
  63. data/lib/scout/llm/chat/provenance.rb +343 -676
  64. data/lib/scout/llm/chat.rb +8 -2
  65. data/lib/scout/llm/embed.rb +15 -3
  66. data/lib/scout/llm/image.rb +4 -1
  67. data/lib/scout/llm/mcp.rb +4 -2
  68. data/lib/scout/llm/request_context.rb +234 -0
  69. data/lib/scout/llm/sandbox.rb +263 -0
  70. data/lib/scout/llm/tools/call.rb +163 -42
  71. data/lib/scout/llm/tools/definition.rb +48 -0
  72. data/lib/scout/llm/tools/knowledge_base.rb +1 -0
  73. data/lib/scout/llm/tools/mcp.rb +50 -43
  74. data/lib/scout/llm/tools/workflow.rb +90 -20
  75. data/lib/scout/llm/tools.rb +14 -41
  76. data/lib/scout/model/decision/base.rb +43 -0
  77. data/lib/scout/model/decision/jev.rb +161 -0
  78. data/lib/scout/model/python/torch.rb +1 -1
  79. data/research/clear-tools-inherit.md +171 -0
  80. data/research/path-engine-dc1-dc2-dc3-fixes.md +279 -0
  81. data/research/path-kind-chat-role.md +96 -0
  82. data/research/path-kind-contract-fixes-engine.md +307 -0
  83. data/research/scout-ai-runtime-availability.md +65 -0
  84. data/research/subsys/README.md +127 -0
  85. data/research/subsys/agent-delegation.md +201 -0
  86. data/research/subsys/agent-society.md +275 -0
  87. data/research/subsys/agentworkflow.md +233 -0
  88. data/research/subsys/backends.md +221 -0
  89. data/research/subsys/chat.md +314 -0
  90. data/research/subsys/embed-image.md +244 -0
  91. data/research/subsys/entry-cli.md +253 -0
  92. data/research/subsys/model-ml.md +326 -0
  93. data/research/subsys/provenance.md +290 -0
  94. data/research/subsys/tools.md +334 -0
  95. data/scout-ai.gemspec +71 -27
  96. data/scout_commands/agent/ask +8 -7
  97. data/scout_commands/llm/abridged +40 -0
  98. data/scout_commands/llm/ask +9 -9
  99. data/scout_commands/llm/md +2 -0
  100. data/scout_commands/llm/prov +724 -59
  101. data/scout_commands/llm/word +4 -0
  102. data/share/word/reference.docx +0 -0
  103. data/test/integration/scout/model/decision/test_jev.rb +144 -0
  104. data/test/scout/llm/agent/test_attach.rb +117 -0
  105. data/test/scout/llm/agent/test_conversation.rb +407 -0
  106. data/test/scout/llm/agent/test_delegate.rb +209 -0
  107. data/test/scout/llm/agent/test_path.rb +1812 -0
  108. data/test/scout/llm/agent/test_path_edit.rb +908 -0
  109. data/test/scout/llm/agent/test_path_errors.rb +390 -0
  110. data/test/scout/llm/agent/test_path_filesystem.rb +532 -0
  111. data/test/scout/llm/agent/test_path_patch.rb +233 -0
  112. data/test/scout/llm/agent/test_path_promotion.rb +386 -0
  113. data/test/scout/llm/agent/test_path_workflow_integration.rb +665 -0
  114. data/test/scout/llm/agent/test_save.rb +70 -15
  115. data/test/scout/llm/agent/test_workflow.rb +130 -4
  116. data/test/scout/llm/backends/test_anthropic.rb +4 -4
  117. data/test/scout/llm/backends/test_bedrock.rb +4 -4
  118. data/test/scout/llm/backends/test_format_other.rb +43 -0
  119. data/test/scout/llm/backends/test_ollama.rb +2 -2
  120. data/test/scout/llm/backends/test_openwebui.rb +12 -8
  121. data/test/scout/llm/backends/test_reasoning.rb +114 -0
  122. data/test/scout/llm/chat/agent_meta_fixtures.rb +28 -27
  123. data/test/scout/llm/chat/prompt/test_epoch_tool_compactation.rb +612 -0
  124. data/test/scout/llm/chat/prov_plot_fixtures.rb +131 -0
  125. data/test/scout/llm/chat/test_agent_meta.rb +40 -80
  126. data/test/scout/llm/chat/test_agent_meta_provenance.rb +67 -28
  127. data/test/scout/llm/chat/test_agent_meta_tokens.rb +59 -8
  128. data/test/scout/llm/chat/test_agent_view.rb +178 -0
  129. data/test/scout/llm/chat/test_live_report.rb +282 -0
  130. data/test/scout/llm/chat/test_live_workload.rb +193 -0
  131. data/test/scout/llm/chat/test_parse.rb +32 -2
  132. data/test/scout/llm/chat/test_prompt.rb +411 -0
  133. data/test/scout/llm/chat/test_prov_cli.rb +310 -15
  134. data/test/scout/llm/chat/test_prov_cli_live.rb +152 -0
  135. data/test/scout/llm/chat/test_prov_plot.rb +213 -0
  136. data/test/scout/llm/chat/test_prov_timeline.rb +355 -0
  137. data/test/scout/llm/chat/test_provenance.rb +67 -22
  138. data/test/scout/llm/chat/test_provenance_index.rb +479 -0
  139. data/test/scout/llm/chat/test_society_view.rb +159 -0
  140. data/test/scout/llm/test_agent.rb +1 -1
  141. data/test/scout/llm/test_embed.rb +103 -1
  142. data/test/scout/llm/test_request_context.rb +299 -0
  143. data/test/scout/llm/test_sandbox.rb +249 -0
  144. data/test/scout/llm/tools/test_agent_pairing.rb +150 -0
  145. data/test/scout/llm/tools/test_call_delegation_conflict.rb +316 -0
  146. data/test/scout/llm/tools/test_definition.rb +332 -0
  147. data/test/scout/llm/tools/test_jobs_file.rb +211 -0
  148. data/test/scout/llm/tools/test_mcp.rb +37 -8
  149. data/test/scout/llm/tools/test_workflow.rb +45 -1
  150. data/test/scout/model/decision/test_jev.rb +453 -0
  151. data/test/scout/model/python/huggingface/causal/test_next_token.rb +7 -10
  152. data/test/scout/model/python/huggingface/test_causal.rb +11 -2
  153. data/test/scout/model/python/huggingface/test_classification.rb +5 -3
  154. data/test/scout/model/python/test_availability.rb +116 -0
  155. data/test/scout/model/python/test_torch.rb +54 -2
  156. data/test/support/availability.rb +72 -174
  157. data/test/support/fake_clients.rb +18 -9
  158. data/test/support/fixtures.rb +75 -6
  159. data/test/support/mock_backend.rb +9 -1
  160. data/test/support/test_fixtures.rb +156 -0
  161. data/test/test_helper.rb +14 -4
  162. metadata +70 -26
  163. data/research/ChatAnalyst-required-changes.md +0 -167
  164. data/research/agent-delegation-analysis.md +0 -810
  165. data/research/agent-meta-provenance-integration-plan.md +0 -622
  166. data/research/agent-workflow-analysis.md +0 -1120
  167. data/research/backends-analysis.md +0 -836
  168. data/research/chat-core-analysis.md +0 -946
  169. data/research/chatanalyst-provenance/00-baseline.md +0 -30
  170. data/research/chatanalyst-provenance/01-repo-map.md +0 -60
  171. data/research/chatanalyst-provenance/02-event-reconstruction.md +0 -55
  172. data/research/chatanalyst-provenance/03-duplication-evidence.md +0 -45
  173. data/research/chatanalyst-provenance/04-tooling-root-cause.md +0 -57
  174. data/research/chatanalyst-provenance/05-fix-plan.md +0 -46
  175. data/research/chatanalyst-provenance/07-critic-review.md +0 -25
  176. data/research/chatanalyst-provenance/final-report.md +0 -45
  177. data/research/chatanalyst-provenance/resumption.md +0 -37
  178. data/research/coding-philosophy-analysis.md +0 -928
  179. data/research/commands-analysis.md +0 -947
  180. data/research/multi-agent-patterns-analysis.md +0 -853
  181. data/research/prompt-strategies-analysis.md +0 -630
  182. data/research/prov-verbosity-fix-notes.md +0 -77
  183. data/research/provenance-analysis.md +0 -469
  184. data/research/provenance-continuation-accounting.md +0 -255
  185. data/research/synthesis-report.md +0 -487
  186. data/research/tools-system-analysis.md +0 -779
@@ -6,8 +6,8 @@ contributors.
6
6
 
7
7
  > For the user-facing guide on what happens when contexts get long, see
8
8
  > [../user/ManagingContext.md](../user/ManagingContext.md).
9
- > For deep code investigation, see
10
- > [../../research/prompt-strategies-analysis.md](../../research/prompt-strategies-analysis.md).
9
+ > There is no `research/subsys/` study for this subsystem yet; this page is
10
+ > the deep reference, and the code remains the source of truth.
11
11
 
12
12
  ---
13
13
 
@@ -21,36 +21,38 @@ amounts of tokens.
21
21
 
22
22
  The system works by applying named "strategies" to the message array. Each
23
23
  strategy is a function that takes an Array of message hashes and returns a
24
- (possibly shorter or modified) Array.
24
+ (possibly shorter or modified) Array of message hashes.
25
25
 
26
26
  ---
27
27
 
28
28
  ## File layout
29
29
 
30
- Strategy implementations live in `lib/scout/llm/prompt/`:
30
+ Strategy implementations live in `lib/scout/llm/chat/prompt/`:
31
31
 
32
32
  ```
33
- lib/scout/llm/
34
- ├── chat/
35
- │ └── prompt.rb # Dispatcher: prepare_prompt, shared constants
33
+ lib/scout/llm/chat/
34
+ ├── prompt.rb # Dispatcher: prepare_prompt, shared constants
36
35
  └── prompt/
37
- ├── shorten_tools.rb # Default strategy (recomputes each turn)
38
- └── shorten_tools_epoch.rb # Cache-friendly epoch variant
36
+ ├── shorten_tools.rb # Recomputes the truncation each turn
37
+ ├── shorten_tools_epoch.rb # Cache-friendly epoch variant
38
+ ├── shorten_tools_epoch_increment.rb # Epochs + growing compacted window
39
+ ├── epoch_tool_compactation.rb # Epoch schedule; oversized pairs removed and replaced by metadata records (DEFAULT)
40
+ └── inbox.rb # Consume-once message inbox (NOT ephemeral)
39
41
  ```
40
42
 
41
- The dispatcher in `prompt.rb` requires both strategy files and delegates to
43
+ The dispatcher in `prompt.rb` requires the strategy files and delegates to
42
44
  them via a `case` statement inside `prepare_prompt`.
43
45
 
44
46
  ---
45
47
 
46
- ## The ephemeral design
48
+ ## The ephemeral design (and the one deliberate exception)
47
49
 
48
- **Prompt strategies never mutate the stored chat.** The transformation happens
49
- entirely inside the backend's `ask` method:
50
+ **With one exception, prompt strategies never mutate the stored chat.** The
51
+ transformation happens entirely inside the backend's `ask` method:
50
52
 
51
53
  ```ruby
52
54
  # lib/scout/llm/backends/default.rb
53
- prompt = Chat.prepare_prompt(messages, prompt_strategies)
55
+ prompt = Chat.prepare_prompt(messages, prompt_strategies, save_file: save_file)
54
56
  ```
55
57
 
56
58
  The variable `prompt` is a local derived from `messages`. The original messages
@@ -63,12 +65,16 @@ and the underlying Chat Object are untouched. This means:
63
65
  This deliberately decouples *what the model sees* from *what the system
64
66
  remembers*.
65
67
 
68
+ **The exception is `inbox`** (see below): it moves consumed files on disk
69
+ (side effects survive the inference), although it still never touches the
70
+ stored chat transcript.
71
+
66
72
  ---
67
73
 
68
74
  ## `prepare_prompt` entry point
69
75
 
70
76
  ```ruby
71
- def self.prepare_prompt(prompt, prompt_strategies = nil)
77
+ def self.prepare_prompt(prompt, prompt_strategies = nil, save_file: nil)
72
78
  ```
73
79
 
74
80
  The method supports four input forms for `prompt_strategies`:
@@ -76,20 +82,22 @@ The method supports four input forms for `prompt_strategies`:
76
82
  | Input type | Behavior |
77
83
  |---|---|
78
84
  | `Proc` | Called directly with the prompt array — full custom hook. |
79
- | `nil` | Falls back to `DEFAULT_CONTEXT_STRATEGY` = `%w(shorten_tools)`. |
80
- | `String` | Split by comma into strategy names (e.g., `"shorten_tools,custom"`). |
85
+ | `nil` | Falls back to `Scout::Config` (`prompt_strategies`, env `PROMPT_STRATEGY`), then `DEFAULT_CONTEXT_STRATEGY` = `['epoch_tool_compactation','inbox']`. |
86
+ | `String` | Split by comma into strategy names (e.g., `"inbox,epoch_tool_compactation"`). |
81
87
  | `Array<String>` | Apply each named strategy in sequence. |
82
88
 
83
- Strategies are applied **in sequence**: each receives the output of the previous.
89
+ Strategies are applied **in sequence**: each receives the output of the
90
+ previous.
84
91
 
85
92
  The string `"none"` is a recognized no-op that returns the prompt unchanged.
86
93
 
87
- ---
94
+ `save_file` is an optional chat-level context (the file the chat is saved to).
95
+ It is forwarded to the strategies that declare the keyword — the single-argument
96
+ `shorten_*` strategies are unaffected — and is currently consumed by `inbox`.
88
97
 
89
- ## The `shorten_tools` strategy (default)
98
+ ---
90
99
 
91
- This is the **default strategy** — it runs on every backend `ask` call unless
92
- explicitly disabled.
100
+ ## The `shorten_tools` strategy
93
101
 
94
102
  ### Algorithm
95
103
 
@@ -121,16 +129,23 @@ There is also a character-budget override: if cumulative tool content is below
121
129
  This means **short conversations are never truncated** — the system is a no-op
122
130
  until context pressure is real.
123
131
 
132
+ A second guard, easy to miss from the counters table alone: both keep-tests
133
+ also read `user_messages == 0`. The counter starts at 1 and increments only
134
+ when a `user` message is passed, so during the reverse (newest-first) walk
135
+ every tool message met before the *first earlier user message* still sees
136
+ `user_messages == 0` and is kept at full fidelity — the whole newest user
137
+ turn is protected, whatever the age of the tool messages inside it.
138
+
124
139
  ---
125
140
 
126
141
  ## The `shorten_tools_epoch` strategy (cache-friendly)
127
142
 
128
143
  ### Motivation
129
144
 
130
- The default `shorten_tools` strategy recomputes the truncation boundary on
131
- **every single inference**. When a new tool call is added, the boundary shifts
132
- by one position, causing every previously-truncated message to be re-evaluated
133
- with a different offset. This means the prompt prefix changes on every turn,
145
+ `shorten_tools` recomputes the truncation boundary on **every single
146
+ inference**. When a new tool call is added, the boundary shifts by one
147
+ position, causing every previously-truncated message to be re-evaluated with a
148
+ different offset. This means the prompt prefix changes on every turn,
134
149
  **defeating KV-cache and prompt-cache mechanisms** offered by LLM providers.
135
150
 
136
151
  `shorten_tools_epoch` solves this by **freezing the compaction boundary** for
@@ -149,73 +164,253 @@ The conversation is divided into four regions (newest at the bottom):
149
164
  [ full-new ] any tool calls that arrived after the epoch boundary (full fidelity)
150
165
  ```
151
166
 
152
- The `compacted` and `full-recent` regions are **pinned** relative to the epoch
153
- boundary, not the live tool-call count. Their content stays stable until the
154
- boundary advances.
167
+ ### Configuration
155
168
 
156
- ### Epoch boundary calculation
169
+ | Config key | ENV var | Default | Description |
170
+ |---|---|---|---|
171
+ | `epoch_tool_call_threshold` | `EPOCH_TOOL_CALL_THRESHOLD` | 50 | Total tool calls at or below which no compaction happens |
172
+ | `epoch_full_tool_calls` | `EPOCH_FULL_TOOL_CALLS` | 20 | Most-recent tool calls kept at full fidelity |
173
+ | `epoch_compacted_tool_calls` | `EPOCH_COMPACTED_TOOL_CALLS` | 80 | Tool calls (before full-recent) to truncate |
174
+ | `epoch_size` | `EPOCH_SIZE` | 20 | New tool calls allowed before boundary advances |
157
175
 
158
- ```
159
- overflow = total_tool_calls - threshold # how many beyond threshold
160
- epoch_idx = overflow > 0 ? (overflow - 1) / epoch_size : 0
161
- pinned_total = threshold + (epoch_idx * epoch_size)
162
- new_calls = total_tool_calls - pinned_total # tool calls that arrived this epoch
163
- ```
176
+ All thresholds are read via `Scout::Config.get` and memoized in class
177
+ variables, following the same pattern as `shorten_tools`.
164
178
 
165
- The `pinned_total` determines where the `full-recent` region starts. Any tool
166
- calls beyond `pinned_total` are treated as "new" and kept at full fidelity.
179
+ ---
167
180
 
168
- ### Worked example (threshold=100, full=10, compacted=40, epoch_size=10)
181
+ ## The `shorten_tools_epoch_increment` strategy
169
182
 
170
- | Tool calls | pinned_total | new_calls | keep_full | compacted | dropped |
171
- |---|---|---|---|---|---|
172
- | 100 | 100 | 0 | 10 | 40 | 50 |
173
- | 101 | 100 | 1 | 11 | 40 | 50 |
174
- | 105 | 100 | 5 | 15 | 40 | 50 |
175
- | 110 | 100 | 10 | 20 | 40 | 50 |
176
- | 111 | 110 | 1 | 11 | 40 | 60 |
183
+ Not the default anymore, but still selectable by name (`PROMPT_STRATEGY`,
184
+ `prompt_strategies`). It is the strategy whose epoch schedule
185
+ `epoch_tool_compactation` reuses verbatim (see the next section).
177
186
 
178
- From tool calls 101–110 the compacted region (calls 11–50 from the pinned
179
- boundary) is **identical**, so the prompt prefix is cache-stable for 10
180
- consecutive inferences. At call 111 the boundary advances and the compacted
181
- region shifts.
187
+ It keeps the epoch-frozen compaction boundary of `shorten_tools_epoch` and
188
+ grows two windows over the life of the conversation: the epoch size itself
189
+ (periodically, and additionally whenever an epoch contains repeated calls) and,
190
+ for each extra call of effective epoch size, the compacted region (growth ratio
191
+ 2.0, capped at 160 compacted calls). The amount of retained truncated history
192
+ therefore increases as the conversation lengthens, instead of always resetting
193
+ to a fixed window. Inside the compacted window, oversized calls and outputs are
194
+ **shortened in place** (`CONTEXT-COMPACTED` previews via `Chat.shorten_string`,
195
+ 400 chars for outputs, 200 chars per string argument value) with tool names
196
+ prefixed `compacted-`; older interactions are dropped entirely.
182
197
 
183
- ### Configuration
198
+ Key extra constants (all read through `Scout::Config` accessors on
199
+ `Chat.prompt`/`context`, same memoization pattern):
184
200
 
185
201
  | Config key | ENV var | Default | Description |
186
202
  |---|---|---|---|
187
- | `epoch_tool_call_threshold` | `EPOCH_TOOL_CALL_THRESHOLD` | 50 | Total tool calls at or below which no compaction happens |
188
- | `epoch_full_tool_calls` | `EPOCH_FULL_TOOL_CALLS` | 10 | Most-recent tool calls kept at full fidelity |
189
- | `epoch_compacted_tool_calls` | `EPOCH_COMPACTED_TOOL_CALLS` | 40 | Tool calls (before full-recent) to truncate |
190
- | `epoch_size` | `EPOCH_SIZE` | 10 | New tool calls allowed before boundary advances |
203
+ | `epoch_tool_call_threshold` | `EPOCH_TOOL_CALL_THRESHOLD` | 50 | No compaction below this many tool calls |
204
+ | `epoch_full_tool_calls` | `EPOCH_FULL_TOOL_CALLS` | 20 | Most-recent full-fidelity tool calls |
205
+ | `epoch_compacted_tool_calls` | `EPOCH_COMPACTED_TOOL_CALLS` | 80 | Compacted window size at epoch start |
206
+ | `epoch_size` | `EPOCH_SIZE` | 20 | Initial epoch size |
207
+ | `epoch_increment_epochs_per_increase` | `EPOCH_INCREMENT_EPOCHS_PER_INCREASE` | 3 | Completed epochs before the epoch grows |
208
+ | `epoch_increment_size_increase` | `EPOCH_INCREMENT_SIZE_INCREASE` | 10 | Periodic epoch-size increase |
209
+ | `epoch_increment_repeat_increase` | `EPOCH_INCREMENT_REPEAT_INCREASE` | 10 | Epoch-size increase for epochs with repeated calls |
210
+ | `epoch_increment_max_size` | `EPOCH_INCREMENT_MAX_SIZE` | 60 | Upper bound for epoch growth |
211
+ | `epoch_increment_compacted_growth_ratio` | `EPOCH_INCREMENT_COMPACTED_GROWTH_RATIO` | 2.0 | Extra compacted calls retained per extra epoch call |
212
+ | `epoch_increment_max_compacted_tool_calls` | `EPOCH_INCREMENT_MAX_COMPACTED_TOOL_CALLS` | 160 | Upper bound of the grown compacted window |
213
+
214
+ Turning compaction off entirely (drop-only) requires zeroing the base window
215
+ **and** its growth: `epoch_compacted_tool_calls = 0` alone is not enough,
216
+ because the growth ratio re-populates the compacted region as epochs grow
217
+ (base 0 with the default ratio 2.0 yields 60 compacted calls by 400 tool
218
+ calls). Either also set `epoch_increment_compacted_growth_ratio = 0`, or pin
219
+ the whole window with `epoch_increment_max_compacted_tool_calls = 0` — the cap
220
+ is applied after growth, so it dominates every growth path. Keep
221
+ `epoch_full_tool_calls > 0`: with full AND base both at 0 the strategy
222
+ disables itself and nothing is ever dropped.
223
+
224
+ Like the other shorten strategies it is **ephemeral**: it only changes what
225
+ the model sees; the stored chat keeps full fidelity.
226
+
227
+ ---
191
228
 
192
- All thresholds are read via `Scout::Config.get` and memoized in class variables,
193
- following the same pattern as `shorten_tools`.
229
+ ## The `epoch_tool_compactation` strategy (default)
230
+
231
+ This is the **current default** (first element of `DEFAULT_CONTEXT_STRATEGY =
232
+ ['epoch_tool_compactation','inbox']`, `lib/scout/llm/chat/prompt.rb`). It
233
+ reuses the `shorten_tools_epoch_increment` epoch schedule unchanged — same
234
+ config keys, same ENV vars, same windows (`Chat.build_epoch_increment_repeat_data`
235
+ / `Chat.build_epoch_increment_schedule`) — and changes only what happens to an
236
+ interaction inside the compacted window: an oversized pair stops being
237
+ represented as a tool interaction at all.
238
+
239
+ **Trigger** (strictly-greater, matching `Chat.shorten_string`'s no-op
240
+ semantics at or under the limit): a pair is oversized when the output
241
+ `content.to_s.length > DEFAULT_SHORT_STRING_LENGTH * 2` (400) or **any**
242
+ argument value is a String with `length > DEFAULT_SHORT_STRING_LENGTH` (200).
243
+
244
+ **Classification by the schedule's tool position** (1-based on outputs, newest
245
+ first):
246
+
247
+ - protected position (repeated call, most recent instance) or within the full
248
+ window → kept at full fidelity regardless of size;
249
+ - inside the compacted window and oversized → **both messages of the pair
250
+ removed**, replaced by one metadata record at the position where the pair's
251
+ output stood; sub-threshold pairs stay byte-identical (no `compacted-`
252
+ renames, ids of survivors never modified);
253
+ - older than the grown compacted window → **both messages dropped** with no
254
+ per-pair record (same drop semantics as the epoch strategies).
255
+
256
+ **Record format** — one role `:user` message carrying `compacted: true` and
257
+ text that begins with the `TOOL_COMPACTATION_MESSAGE` marker and contains: the
258
+ exact original tool name; the call id as plain text; the original sizes
259
+ (arguments total chars, output chars); the identifying arguments; one line
260
+ `Full output found in job: <step>` only when the output carried a `step`
261
+ (workflow/job tools only — set at `lib/scout/llm/tools/call.rb:293-298`,
262
+ value `Step#short_path`); and a closing sentence stating the pair was removed,
263
+ the record is metadata not a tool result, and the tool should be re-run if the
264
+ value is needed. The record never contains a `Preview:` and never a truncation
265
+ of a value.
266
+
267
+ **Exact-or-omitted argument rule**: each argument entry is rendered `key=value`
268
+ exactly when the value is a String of at most `DEFAULT_SHORT_STRING_LENGTH`
269
+ (200) chars or a scalar (Integer, Float, Symbol, `true`/`false`/`nil`);
270
+ anything else renders as `key=<omitted, N chars>`. Exact or omitted, nothing
271
+ in between — a truncated, executable-looking command can never appear.
272
+
273
+ **Orphans and malformed pairs**: a call without its output (or the reverse)
274
+ and a pair whose content JSON does not parse are left completely untouched —
275
+ they are never replaced, dropped, or renamed — but still count toward the
276
+ interaction totals so the schedule matches what the epoch strategies would
277
+ compute. Outputs with a blank id are paired by adjacency (universal in real
278
+ layouts).
279
+
280
+ **Global notice**: when at least one pair was replaced or dropped, one fixed,
281
+ counter-free `:user` message is prepended at index 0 stating that historical
282
+ tool interactions may be omitted and compaction records are metadata, not tool
283
+ results. The text is deliberately free of counters so the prompt prefix stays
284
+ byte-stable between rounds and provider prompt caches remain valid.
285
+
286
+ Like the other strategies it is **ephemeral**: the stored chat keeps every
287
+ interaction at full fidelity; only what the model sees changes. Tests:
288
+ `test/scout/llm/chat/prompt/test_epoch_tool_compactation.rb` (17 cases).
194
289
 
195
- ### Enabling the epoch strategy
290
+ ---
196
291
 
197
- To use it instead of the default, pass the strategy name:
292
+ ## The `inbox` strategy (consume-once message inbox)
293
+
294
+ `inbox` is the one strategy that deliberately breaks the ephemerality
295
+ contract: it has **side effects on disk** (it moves files), although it still
296
+ never writes to the chat transcript.
297
+
298
+ ### What it does
299
+
300
+ On every real inference, when the chat has a `save_file`:
301
+
302
+ 1. Lists the regular files in the chat's inbox directory (dotfiles and
303
+ subdirectories ignored), sorted by filename for deterministic delivery
304
+ order.
305
+ 2. For each file, **moves it first** into the matching `.inbox_removed`
306
+ sibling (created lazily at the moment of the first move; a name collision
307
+ gets a `.1`, `.2`, ... suffix so previous deliveries are never
308
+ overwritten), then reads it and appends
309
+ `{ role: 'user', content: <file content> }` to the outgoing prompt.
310
+ 3. The file's mtime is preserved through the move.
311
+
312
+ ### Reserved filename: `abort`
313
+
314
+ `abort` (exactly, no extension, case-sensitive) is a reserved inbox filename:
315
+ when the sorted pickup reaches it, the file is consumed like any other (moved
316
+ into `.inbox_removed`, mtime preserved, exactly once) but its content is
317
+ **never appended to the prompt**. Instead the strategy raises the
318
+ framework-native `Aborted` exception (`scout-essentials`
319
+ `lib/scout/exceptions.rb`, the class scout-gear's `Step` raises for SIGTERM
320
+ and records as `:aborted` rather than `:error`), so the surrounding job ends
321
+ up visibly interrupted instead of silently succeeding. The stripped file
322
+ content becomes the abort reason (blank content falls back to a reason
323
+ carrying the consumed file's path).
324
+
325
+ Files that sort **before** `abort` in the same pickup have already been
326
+ consumed normally (moved and appended; those appends are lost with the raise,
327
+ they are not re-delivered); files sorting **after** it stay in the inbox for
328
+ the next run. No other filename is special: `abort.txt`, `Abort`, or a file
329
+ whose name merely contains the word are delivered as ordinary messages.
330
+
331
+ **Move-before-append is deliberate**: a crash between the move and the read
332
+ may silently drop a notice, but can never deliver the same notice twice.
333
+ Delivery is at-most-once, not exactly-once.
334
+
335
+ ### Gating
336
+
337
+ - No `save_file` (or blank) → returns messages untouched.
338
+ - Inbox directory missing → silent no-op. **The read path never creates
339
+ directories**: writers (you) create the `<stem>.inbox` sibling when there is
340
+ something to deliver, ideally by writing the file elsewhere and renaming it
341
+ in, so a reader never sees a half-written file.
342
+
343
+ ### Paths (the sibling rule)
344
+
345
+ The inbox is a **sibling of the chat's save_file**, in the save_file's own
346
+ directory. The rule: take the save_file basename, strip its **last**
347
+ extension if one exists (an extension-less basename keeps the whole name),
348
+ and append the suffix:
349
+
350
+ | save_file | inbox | removed log |
351
+ |---|---|---|
352
+ | `<X>.files/agent.chat` | `<X>.files/agent.inbox` | `<X>.files/agent.inbox_removed` |
353
+ | `dir/a.b.chat` | `dir/a.b.inbox` | `dir/a.b.inbox_removed` |
354
+ | `dir/agent` (no extension) | `dir/agent.inbox` | `dir/agent.inbox_removed` |
355
+
356
+ Use `Chat.inbox_dir(save_file)` / `Chat.inbox_removed_dir(save_file)` rather
357
+ than deriving the paths by hand.
358
+
359
+ ### Robustness
360
+
361
+ Per-file handling is isolated: an unreadable or unmovable file is skipped in
362
+ place (logged at low severity) and never raises into the ask path; the other
363
+ files are still delivered. Strategies never let a filesystem hiccup break an
364
+ inference.
365
+
366
+ ### Semantics to be aware of
367
+
368
+ - **Injected messages are not persisted**: the model sees them, the saved
369
+ chat file does not. The `.inbox_removed` sibling (with preserved mtimes) is
370
+ the record of what was delivered and when.
371
+ - **Cache hits skip the inbox**. `prepare_prompt` runs inside the backend,
372
+ after `LLM.ask`'s persistence layer. A cached answer is replayed without
373
+ any backend code running, so inbox files are neither seen nor consumed on
374
+ that call; they stay for the next real inference.
375
+ - **Tool-call rounds**: `prepare_prompt` runs once per round, including every
376
+ `chain_tools` re-entry within one logical turn. The strategy list is
377
+ re-threaded through `chain_tools` like `save_file`, so a user-specified list
378
+ applies on every round. Because a file is moved on consumption, a notice
379
+ delivered on round 1 is not re-delivered on round 2.
380
+ - **Invisible to provenance**: the `.inbox` and `.inbox_removed` siblings are
381
+ not matched by the chat-file globs in `Chat::DIRECT_LOG_CHAT_GLOBS`
382
+ (`'*.chat'`, `'*.society/**/*.chat'`), so inbox files are never mistaken
383
+ for chat logs.
384
+
385
+ ### Enabling
386
+
387
+ `inbox` is part of `DEFAULT_CONTEXT_STRATEGY`, so it is **on by default** for
388
+ every chat that passes a `save_file`. You only need to name it when you want
389
+ to *extend* the default list (a user-supplied `prompt_strategies` **replaces**
390
+ the default rather than appending to it), or to *reorder* it:
198
391
 
199
392
  ```ruby
200
- # In options
201
- options[:prompt_strategies] = 'shorten_tools_epoch'
393
+ # In chat options (delivered notices are unaffected by the shortener, but
394
+ # inbox-first keeps the semantics obvious)
395
+ options[:prompt_strategies] = 'inbox,epoch_tool_compactation'
202
396
 
203
- # Or directly
204
- Chat.prepare_prompt(messages, 'shorten_tools_epoch')
397
+ # Or in a chat file:
398
+ # option prompt_strategies inbox,epoch_tool_compactation
205
399
  ```
206
400
 
207
- To switch the default system-wide, set:
401
+ To disable it, set `prompt_strategies` to a list without `inbox` (the string
402
+ `"none"` is the recognized no-op that turns every strategy off).
208
403
 
209
- ```ruby
210
- Chat::DEFAULT_CONTEXT_STRATEGY.replace(['shorten_tools_epoch'])
211
- ```
404
+ See [../user/ManagingContext.md](../user/ManagingContext.md) for the
405
+ user-facing story.
212
406
 
213
407
  ---
214
408
 
215
- ## Configuration thresholds (`shorten_tools`)
409
+ ## Configuration thresholds (`shorten_tools`, non-default)
216
410
 
217
- All thresholds are read via `Scout::Config.get` and **memoized** in class
218
- variables on first access:
411
+ `shorten_tools` is **not** in the default strategy list; the numbers below
412
+ apply only when you select it explicitly. All thresholds are read via
413
+ `Scout::Config.get` and **memoized in class variables** on first access:
219
414
 
220
415
  | Config key | ENV var | Default | Description |
221
416
  |---|---|---|---|
@@ -225,6 +420,12 @@ variables on first access:
225
420
  | `max_tool_outputs` | `MAX_TOOL_OUTPUTS` | 40 (defaults to `max_tool_calls`) | Hard limit; outputs beyond this are dropped |
226
421
  | `max_tool_chars` | `MAX_TOOL_CHARS` | 100,000 | Cumulative character budget for retained tool content |
227
422
 
423
+ These are `shorten_tools`' own limits. They are not the default-strategy
424
+ bounds (the epoch schedule shared by `shorten_tools_epoch_increment` and
425
+ `epoch_tool_compactation` is tabulated above: threshold 50, 20 full, 80
426
+ compacted) and they are not a request round limit — the ask loop has no round
427
+ counter.
428
+
228
429
  ### Memoization trade-off
229
430
 
230
431
  Because thresholds use `||=` memoization, they are **frozen for the process
@@ -239,7 +440,7 @@ long-running daemons.
239
440
  When a value is truncated, `Log.truncate_string` embeds an MD5 hash prefix:
240
441
 
241
442
  ```
242
- Truncated (15432): The first ~70 chars...<...15432 - a1b2c...>...last ~70 chars
443
+ Truncated (15432): The first ~70 chars...<...15432 - a1b2c3...>...last ~70 chars
243
444
  ```
244
445
 
245
446
  This allows truncated content to be matched against logs or the original chat
@@ -249,20 +450,26 @@ for debugging.
249
450
 
250
451
  ## Integration with the backend
251
452
 
252
- `prepare_prompt` is called inside `Backend::Default#ask`, in the normal
453
+ `prepare_prompt` is called inside `Backend::ClassMethods#ask`, in the normal
253
454
  (non-relay) path:
254
455
 
255
456
  ```ruby
256
457
  client = prepare_client(options, messages)
257
- prompt = Chat.prepare_prompt(messages, prompt_strategies)
458
+ prompt = Chat.prepare_prompt(messages, prompt_strategies, save_file: save_file)
258
459
  formatted_prompt = format_messages(prompt)
259
460
  tools = tools(formatted_prompt, options)
260
461
  response = query(client, formatted_prompt, tools, options)
261
462
  ```
262
463
 
263
464
  Key points:
264
- - Applied on every `ask` invocation in the normal path.
465
+ - Applied on every `ask` invocation in the normal path, **including every
466
+ `chain_tools` re-entry round** (the strategy list is re-threaded through the
467
+ `chain_tools` options merge alongside `save_file`, so user-specified lists
468
+ apply on every round rather than degrading to the default).
265
469
  - **Not applied in relay mode** (raw messages are uploaded to a remote server).
470
+ - **Not applied on a cache hit**: `LLM.ask`'s `Persist.persist` layer answers
471
+ before any backend code runs. This is the documented reason the `inbox`
472
+ strategy is consume-once *per real inference*, not per logical call.
266
473
  - Applied **before** `format_messages` — strategy output directly determines
267
474
  token consumption.
268
475
  - `prompt_strategies` comes from the `options` hash, so callers can override
@@ -272,16 +479,59 @@ Key points:
272
479
 
273
480
  ## Extension point: custom strategies
274
481
 
275
- Two mechanisms coexist:
482
+ Three mechanisms coexist:
276
483
 
277
- 1. **Hard-coded `case` dispatch** for built-in strategies (`shorten_tools`,
278
- `shorten_tools_epoch`, `none`).
484
+ 1. **Hard-coded `case` dispatch** for the built-in strategies
485
+ (`shorten_tools`, `shorten_tools_epoch`, `shorten_tools_epoch_increment`,
486
+ `epoch_tool_compactation`, `inbox`, `none`).
279
487
  2. **`REGISTERED_STRATEGIES` hash** for user/plugin-registered strategies.
488
+ 3. **`Chat.send(strategy)` fallback**: any unrecognized name is dispatched to
489
+ the Chat class method of the same name, so defining `def self.my_strategy`
490
+ (plus a `require` of its file) makes it selectable without touching the
491
+ dispatcher.
492
+
493
+ > **Note:** `REGISTERED_STRATEGIES` starts empty; nothing in the repo
494
+ > populates it. It is used by tests and plugins. Its procs receive the prompt
495
+ > array only — they do not receive the `save_file:` context; a strategy that
496
+ > needs it belongs in the `case` dispatch or in a Chat class method.
497
+
498
+ ---
280
499
 
281
- > **Note:** `REGISTERED_STRATEGIES` is referenced in the code but not yet
282
- > populated with entries. Passing an unknown strategy name will result in
283
- > `nil.call(prompt)`, raising a `NoMethodError`. For now, use a `Proc` to
284
- > supply custom strategies.
500
+ ## Test anchors
501
+
502
+ The strategy contracts are pinned by `test/scout/llm/chat/test_prompt.rb`
503
+ (20 cases). The most load-bearing ones:
504
+
505
+ - **inbox semantics**: `test_inbox_no_save_file_is_noop_and_creates_nothing`,
506
+ `test_inbox_missing_inbox_dir_is_noop_and_creates_nothing`,
507
+ `test_inbox_dir_derivation_strips_only_the_last_extension`,
508
+ `test_inbox_non_canonical_save_file_uses_the_sibling_rule`,
509
+ `test_inbox_appends_in_sorted_order_moves_files_and_preserves_mtime`,
510
+ `test_inbox_skips_directories_and_dotfiles`,
511
+ `test_inbox_is_consume_once`,
512
+ `test_inbox_collision_in_removed_gets_numeric_suffix`,
513
+ `test_inbox_unreadable_file_is_skipped_without_raising`,
514
+ `test_inbox_returns_chat_annotated_array`.
515
+ - **abort**: `test_inbox_abort_file_aborts_inference_and_is_consumed_once`,
516
+ `test_inbox_abort_file_content_is_the_reason_and_never_reaches_the_prompt`,
517
+ `test_inbox_files_before_abort_are_delivered_and_consumed`,
518
+ `test_inbox_empty_abort_still_aborts_with_default_reason`,
519
+ `test_inbox_non_abort_files_behave_as_before_around_an_abort`.
520
+ - **dispatcher**: `test_prepare_prompt_forwards_save_file_only_to_strategies_that_accept_it`,
521
+ `test_prepare_prompt_registered_proc_ignores_save_file`,
522
+ `test_prompt_strategies_survive_tool_call_re_entry`,
523
+ `test_inbox_composes_with_shorten_tools_epoch_increment_in_both_orders`.
524
+
525
+ No test file pins the numeric thresholds of `shorten_tools` /
526
+ `shorten_tools_epoch` / `shorten_tools_epoch_increment` in isolation; those
527
+ constants live in `lib/scout/llm/chat/prompt/*.rb` and are re-read from
528
+ `Scout::Config` per process (memoized on first access). The default strategy's
529
+ own contract is pinned separately by
530
+ `test/scout/llm/chat/prompt/test_epoch_tool_compactation.rb` (17 cases:
531
+ replacement position, record contents, exact-or-omitted arguments, trigger
532
+ boundaries at 200/201 and 400/401, sub-threshold byte-identity, repeated-call
533
+ protection, orphans and malformed pairs, drop band, stability under repeated
534
+ application, notice gating, and dispatch).
285
535
 
286
536
  ---
287
537
 
@@ -289,4 +539,4 @@ Two mechanisms coexist:
289
539
 
290
540
  - [../user/ManagingContext.md](../user/ManagingContext.md) — User guide for long contexts.
291
541
  - [Backends.md](Backends.md) — Where `prepare_prompt` is called in the inference loop.
292
- - [../../research/prompt-strategies-analysis.md](../../research/prompt-strategies-analysis.md) — Deep investigation.
542
+ - [../../research/subsys/chat.md](../../research/subsys/chat.md) — Chat subsystem study (parsing, roles, compilation); strategies themselves live here.