scout-ai 2.0.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 (185) hide show
  1. checksums.yaml +4 -4
  2. data/.vimproject +135 -55
  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 +320 -34
  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 +402 -44
  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 +64 -0
  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 +79 -17
  39. data/lib/scout/llm/agent.rb +151 -27
  40. data/lib/scout/llm/ask.rb +37 -27
  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 +131 -32
  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 -52
  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 +352 -626
  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 +72 -26
  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 +845 -80
  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 +109 -22
  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 +200 -28
  127. data/test/scout/llm/chat/test_agent_meta_tokens.rb +112 -7
  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 +708 -13
  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 +71 -25
  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/synthesis-report.md +0 -487
  185. data/research/tools-system-analysis.md +0 -779
@@ -7,23 +7,28 @@ framework contributors.
7
7
 
8
8
  > For the user-facing guide to delegation, see
9
9
  > [../user/Delegation.md](../user/Delegation.md).
10
- > For deep code investigation, see
11
- > [../../research/agent-delegation-analysis.md](../../research/agent-delegation-analysis.md).
10
+ > For the probe-verified subsystem study, see
11
+ > [../../research/subsys/agent-delegation.md](../../research/subsys/agent-delegation.md)
12
+ > and [../../research/subsys/agent-society.md](../../research/subsys/agent-society.md).
12
13
 
13
14
  ---
14
15
 
15
16
  ## Overview
16
17
 
17
- Delegation is implemented in `lib/scout/llm/agent/delegate.rb` (323 lines). It
18
- provides two mechanisms for one Agent to invoke another:
18
+ Delegation is implemented in `lib/scout/llm/agent/delegate.rb` and the shared
19
+ conversation pipeline in `lib/scout/llm/agent/conversation.rb` (moved there
20
+ from `delegate.rb`; tool definitions are built by `LLM.tool_definition` in
21
+ `lib/scout/llm/tools/definition.rb`). It provides two mechanisms for one
22
+ Agent to invoke another:
19
23
 
20
24
  1. **`socialize`** — Registers a generic `ask` tool that lets the LLM delegate
21
25
  to any specialist agent by name at runtime.
22
26
  2. **`delegate`** — Registers a named `hand_off_to_<name>` tool for a specific,
23
27
  pre-loaded Agent instance.
24
28
 
25
- Both mechanisms build on a common infrastructure: the **template-clone
26
- pattern**, the **socialized chat store**, and the **inheritance modes**.
29
+ Both mechanisms build on a common infrastructure: the **open_conversation
30
+ pipeline**, the **template-clone pattern**, the **socialized chat store**, and
31
+ the **inheritance modes**.
27
32
 
28
33
  ---
29
34
 
@@ -106,15 +111,8 @@ location from the save target of the *parent* agent:
106
111
  included even though they are also named `agent.chat`. Job roots keep
107
112
  their own top-level `<name>.chat` as a normal log node (renderers hide
108
113
  it), and the `:log` relation covers exactly
109
- `*.files/*.chat`, `*.files/*.society/**/*.chat` and the legacy
110
- `*.files/log/**/*.chat`, so `resets/` snapshots stay out.
111
-
112
- **Legacy layout (read-only).** Older scout-ai wrote
113
- `<chat>.files/log/agent.chat` and the society tree under
114
- `<chat>.files/log/society/<agent_name>/<conversation>/agent.chat`. Nothing
115
- writes there anymore, old files are never migrated, and provenance
116
- traversal still globs `log/**/*.chat` so chats saved by those versions
117
- remain visible.
114
+ `*.files/*.chat` and `*.files/*.society/**/*.chat`, so `resets/` snapshots
115
+ stay out.
118
116
 
119
117
  An agent with no live society writes only its own chat file and creates no
120
118
  `.files` tree at all; parent directories are created on demand by
@@ -123,31 +121,174 @@ parent save, so later independent child turns keep auto-saving in place.
123
121
  Saves are cycle-safe (visited paths + seen agents + a depth limit of 32) and
124
122
  non-fatal: a failure is logged as a warning and the run continues.
125
123
 
126
- ### `load_chat` — get-or-create
124
+ #### Sibling state: the one-derivation convention
125
+
126
+ Every piece of derived agent state is a **sibling of the save_file**, never a
127
+ nested `.files` entry and never an appended suffix on the full chat path. For
128
+ save_file `<dir>/<base>.chat` the siblings are:
129
+
130
+ | Sibling | Written by | Meaning |
131
+ |---|---|---|
132
+ | `<base>.society/` | `Agent#save` (society tree) | delegated conversations, layout above |
133
+ | `<base>.inbox/` | inbox strategy (`Chat.inbox_dir`) | files delivered into the next round |
134
+ | `<base>.inbox_removed/` | `Chat.inbox_removed_target` | delivered files moved out of the inbox, kept with collision suffixes |
135
+ | `<base>.jobs` | `LLM.process_calls` | transient snapshot of in-flight workflow jobs |
136
+
137
+ Derivation strips only a **trailing** `.chat` and appends the suffix
138
+ (`Chat.inbox_stem` + suffix in `lib/scout/llm/chat/prompt/inbox.rb`;
139
+ `Chat.jobs_file` for `.jobs`); an extension-less basename keeps its whole
140
+ name, and a multi-dot base strips only the last extension. The
141
+ `<job>.chat.files/agent.chat` path shape never appears as a state base: the
142
+ canonical agent chat of a job is `<job>.files/<name>.chat`, and its siblings
143
+ are `<job>.files/<name>.inbox` etc.
144
+
145
+ #### Live traceability of delegated work
146
+
147
+ Delegation is observable *while it runs*, not only afterwards:
148
+
149
+ - **Type 4 (ask/hand_off)** — each delegated conversation is its own
150
+ `agent.chat` under the society tree, and `Agent#chat` auto-saves after every
151
+ round, so the file grows round by round while the parent's tool round is
152
+ open. Its sibling inbox is honoured by the child's next real round.
153
+ - **Type 5 (tool-calling delegation)** — `LLM.process_calls` writes the
154
+ caller's `<base>.jobs` sidecar just before `Workflow.produce` and removes it
155
+ in an `ensure`, so the in-flight workload is visible for the whole blocking
156
+ window (child `.info` follows within a fraction of a second of the fork).
157
+ - **Type 3 (chat_task `ask`)** — the chat_task writes an immediate `job=`
158
+ `meta` line into the agent's current_chat and saves agent state *before* the
159
+ task completes, so the job reference exists while the answer is still being
160
+ computed.
161
+
162
+ **Plain agents (no workflow)** never write a `job=` meta at all: their `ask`
163
+ calls `LLM.ask` directly with `save_file: self.save_file`, producing no
164
+ workflow job, so their liveness is observable only through save-file growth.
165
+
166
+ #### The activity predicate
167
+
168
+ The live pass classifies an agent save file from its **trailing
169
+ conversational message**, skipping control roles (`meta`, `option`,
170
+ `sticky_option`, `previous_response_id`, `agent`, `import`, `socialize`,
171
+ `attachments`) so a file that ends with the dispatch-time `meta: job=…`
172
+ line still reads as its real trailing turn. Encoded rules
173
+ (`Chat.agent_log_activity`):
174
+
175
+ | trailing message | verdict |
176
+ |---|---|
177
+ | `user` | active, `:dispatched` |
178
+ | `function_call` with no later `function_call_output` | active, `:tool_round_in_flight` |
179
+ | `function_call_output` | active, `:next_round_pending` |
180
+ | `assistant` with no open call | inactive, `:idle` |
181
+ | empty file | inactive, `:no_messages` |
182
+ | unreadable/missing file | inactive, `:unreadable` |
183
+ | any other role (system, introduce, tool) | inactive, `:no_inference` |
184
+
185
+ `rounds:` is the count of `assistant` messages. The predicate is sound only
186
+ because two writers rewrite the save file on a known cadence: the backend
187
+ writes the outgoing transcript at every round boundary, and the agent layer
188
+ rewrites the completed round afterwards (`Agent#chat` ensure →
189
+ `save_if_configured`). Accepted false negative: an `assistant`-terminated
190
+ file reads idle during the brief round-boundary window in which a completed
191
+ round is saved but the next dispatch is not flushed yet — a mid-conversation
192
+ agent can be missed for that instant, never falsely reported.
193
+
194
+ #### The dangling `job=` meta lifecycle
195
+
196
+ Type-3 dispatch (`Agent#ask` on a workflow-backed agent) writes
197
+ `self.message(:meta, Chat.serialize_meta(job: job.short_path))` and
198
+ immediately `self.save`, both **before** `job.produce` blocks: the reference
199
+ is on disk in the agent's own save file — for a societal child, the society
200
+ child file itself, never the parent's root chat — for exactly the duration
201
+ of the child run, and stays there afterwards pointing at a terminal job.
202
+ The live pass follows these references to jobs and reports only the ones
203
+ that are still running; the parent's root chat gets no `function_call`
204
+ record for the child until the tool round completes, which is why the
205
+ society tree and the child save files, not the parent chat, are the live
206
+ evidence for type 4.
207
+
208
+ #### Waiting wrappers and the dependency fallback
209
+
210
+ `LLM.process_calls` calls `init_info` on every in-flight job **and its
211
+ `rec_dependencies`** before writing the sidecar, so `.info` files exist for
212
+ reconciliation even for dependency-nested running work. But scout-gear
213
+ records a job's `dependencies:` in `.info` only at
214
+ `reset_info(status: :setup)`, which runs after `run_dependencies` returns:
215
+ while a chat_task dependency runs, the wrapper `.info` is still
216
+ `{"status":"waiting"}` — no pid, no dependencies. The live traversal covers
217
+ that window by scanning the wrapper's own workflow namespace
218
+ (`var/jobs/<Workflow>/*/*.info`, sibling task directories; `.info` glob, not
219
+ a directory glob, because a chat_task job path is itself a file) for running
220
+ jobs, reporting the wrapper once as workload context with `state:
221
+ :waiting`. The workflow definition is never loaded (the `workflows` pathmap
222
+ cannot see an arbitrary jobs tree), attribution stays bounded to the
223
+ wrapper's workflow directory, the walk uses direct `dependencies` with a
224
+ visited-path cycle guard plus a depth cap (`LIVE_DEPENDENCY_DEPTH_LIMIT` 5),
225
+ and everything is fail-soft: absent sidecar, absent save file, absent
226
+ society tree and unreadable jobs each yield nothing, never an error.
227
+
228
+ After conclusion the forensic trail takes over: `step:` short paths, receipts
229
+ under the `meta` key of the `function_call_output` envelope, and the projected
230
+ chat_task answer in the conversation. See
231
+ [Provenance.md](Provenance.md#live-work---live) for the consumer side.
232
+
233
+ ### The `open_conversation` pipeline — get-or-create
234
+
235
+ All setup goes through one method (in `lib/scout/llm/agent/conversation.rb`),
236
+ which runs five ordered steps:
127
237
 
128
238
  ```ruby
129
- def load_chat(agent_name, options = {}, conversation = nil, inherit: 'tools')
130
- key = social_chat_key(agent_name, conversation) # "Worker/work_A"
131
- @chats[key] ||= start_social_chat(agent_name, options, inherit)
132
- end
239
+ open_conversation(name, conversation: 'default', inherit: 'tools', options: {},
240
+ preamble: nil, anchor: nil, restart: false,
241
+ template: nil, adopt: nil, job: nil)
133
242
  ```
134
243
 
135
- The `inherit` parameter is only consulted **once** — when the conversation is
136
- first created. Follow-up turns reuse the existing conversation with its
137
- accumulated history.
244
+ 1. **Resolve template** — an explicit `template:` (a pre-built Agent) wins;
245
+ otherwise `load_agent(name, options)` loads and caches one immutable
246
+ template per specialist in `@society`.
247
+ 2. **Seed** — clone via `clone_social_agent`, then build the initial chat:
248
+ the specialist's own `start_chat` copy, optionally the adopted template
249
+ delta (`adopt: :current` folds the template's progress beyond its own
250
+ `start_chat` into the seed), then the inherited context per `inherit:`,
251
+ then any `preamble:`.
252
+ 3. **Anchor** — `agent.save_file = anchor || society_save_file(name,
253
+ conversation)` is assigned at creation, so autosave and `restart:`
254
+ snapshots apply from the first round.
255
+ 4. **Register** — `@chats["<name>/<conversation>"] ||= agent`.
256
+ 5. **Restart** — `restart: true` re-branches the existing conversation in
257
+ place (start_chat kept, tail dropped); no new key is minted.
258
+
259
+ `load_chat`, `load_agent`, and `ask_agent` remain as thin wrappers over this
260
+ pipeline, and `ask_conversation` is the prompt-appending companion.
261
+ `conversation_agent(key)` returns the registered live conversation (nil when
262
+ absent). The `delegate` default hand-off block uses exactly this pipeline
263
+ (conversation slot = the delegated name, `inherit: 'none'`, `template:` the
264
+ passed agent, `adopt: :current`, `restart:` from `new_conversation`), so
265
+ hand-off children persist under
266
+ `<save>.society/<agent>/<slot>/agent.chat` and are swept by the parent save;
267
+ the passed agent object is only the template, not the conversation holder.
268
+ Custom blocks and non-Agent duck objects keep the legacy direct-mutation
269
+ contract. The passed Agent is also pre-registered in `@society[name] ||=`,
270
+ making it the template for later `ask` calls to that name.
271
+
272
+ The `inherit` parameter is consulted **once** for the three creation modes
273
+ (`none`, `tools`, `conversation`) — when the conversation is first created.
274
+ Follow-up turns reuse the existing conversation with its accumulated history.
275
+ The fourth mode, `clear_tools`, is additionally a **continuation-time**
276
+ policy: it seeds like `conversation` at creation and appends a clearing
277
+ marker when the conversation is continued (details below).
138
278
 
139
279
  ---
140
280
 
141
281
  ## SOCIAL_INHERIT_MODES
142
282
 
143
- Three modes control how much caller context flows to a specialist on first
144
- contact:
283
+ Four modes control how much caller context flows to a specialist on first
284
+ contact — `clear_tools` also acts on continuation:
145
285
 
146
286
  | Mode | What is inherited | Use case |
147
287
  |---|---|---|
148
288
  | `none` | Nothing. Specialist starts with its own `start_chat` only. | Fully isolated sub-agent. |
149
- | `tools` *(default)* | Tooling roles (`introduce`, `tool`, `mcp`, `kb`) from the caller's current chat. | Shared capabilities, private history. |
289
+ | `tools` *(default)* | Tooling roles (`introduce`, `tool`, `mcp`, `kb`) from the caller's **whole current chat**. | Shared capabilities, private history. |
150
290
  | `conversation` | The caller's entire current chat minus its own `start_chat` prefix. | Full context sharing for tight collaboration. |
291
+ | `clear_tools` | Seeds exactly like `conversation` at creation; on **continuation** appends `message :clear_tools, true` before the new prompt, dropping the conversation's earlier `function_call`/`function_call_output` from the model context only. | Long delegated conversations whose tool rounds bloat the prompt. |
151
292
 
152
293
  ### Implementation: `social_inherited_context`
153
294
 
@@ -158,13 +299,50 @@ def social_inherited_context(inherit)
158
299
  Chat.setup([])
159
300
  when 'tools'
160
301
  tooling = self.current_chat.tooling
161
- social_chat_copy(tooling)
162
- when 'conversation'
302
+ social_chat_copy(tooling) # whole current chat's tooling — see Known drift
303
+ when 'conversation', 'clear_tools'
163
304
  social_caller_context
164
305
  end
165
306
  end
166
307
  ```
167
308
 
309
+ `clear_tools` shares the `'conversation'` seed: at creation there are no
310
+ earlier bouts of the new conversation to clear.
311
+
312
+ ### `clear_tools` continuation: marker insertion and fallback
313
+
314
+ `ask_conversation` (conversation.rb) checks whether the social key already
315
+ held a live agent **before** calling `open_conversation` (the continuation
316
+ branch), then:
317
+
318
+ - **Continuation, no `restart:`** and `inherit == 'clear_tools'` — appends
319
+ `agent.current_chat.message :clear_tools, true` immediately before
320
+ `agent.user(prompt)`. One marker per continuation call; repeated markers
321
+ are equivalent because `Chat.clear`'s reverse scan sets the drop flag at
322
+ the nearest marker and never resets it.
323
+ - **Creation or `restart: true`** — no marker; seeds like `conversation`
324
+ (a restart re-branches to `start_chat`, so there is nothing to clear) and
325
+ emits one `Log.low` line recording the fallback.
326
+
327
+ The insertion site is `ask_conversation`, not `open_conversation`:
328
+ `load_chat`/`open_conversation` without a following prompt must not fire
329
+ clearing, because there is no new round to compile.
330
+
331
+ **Why the marker does not strip chat-line tool definitions.**
332
+ `Chat.tools`' forward walk resets gathered tool definitions at a
333
+ `clear_tools` role (`tool_definitions = {}`, tools.rb), so a *direct*
334
+ `Chat.tools` call on a marker-bearing chat returns nothing for lines before
335
+ the marker. The ask pipeline never hits that branch with the marker:
336
+ `LLM.chat` runs `Chat.clear` **before** any backend resolves tools
337
+ (backends resolve tools on the post-`clear` message list, where the marker
338
+ and the dropped tool traces are already gone). This consumption order is
339
+ load-bearing — do not reorder `LLM.chat`. Design rationale and probe
340
+ evidence: `research/clear-tools-inherit.md`.
341
+
342
+ **Context-only guarantee.** The marker is consumed at prompt compilation
343
+ only. The stored chat, save files, logs, and provenance records keep the
344
+ marker and every `function_call`/`function_call_output` pair.
345
+
168
346
  ### `social_caller_context` — extracting non-start-chat messages
169
347
 
170
348
  For `conversation` mode, the method extracts the "new" messages the caller
@@ -195,7 +373,7 @@ any specialist:
195
373
  | `agent` | string | Yes | Name of the specialist agent. |
196
374
  | `prompt` | string | Yes | Plain-text prompt. |
197
375
  | `conversation` | string | No | Named conversation ID (omit for one-shot). |
198
- | `inherit` | enum `[none, tools, conversation]` | No (default `tools`) | Context policy for new conversations only. |
376
+ | `inherit` | enum `[none, tools, conversation, clear_tools]` | No (default `tools`) | Context policy. `none`/`tools`/`conversation` apply at creation only. `tools` reads the whole current chat's tooling, not the delegating task's. `clear_tools` also acts on continuation: it drops earlier tool-call traces from the model context only (stored chats keep everything). |
199
377
 
200
378
  **Security boundary:** The tool block calls `ask_agent`, which uses
201
379
  `agent.user(prompt)` rather than `agent.prompt(prompt)`. This is deliberate:
@@ -217,18 +395,99 @@ SOCIAL_PRIVATE_OPTIONS = %i[
217
395
  This prevents leaking session state, tool blocks, or message arrays from the
218
396
  caller to the specialist.
219
397
 
398
+ ### Parallel delegation preflight: one conversation per batch
399
+
400
+ `LLM.process_calls` runs the tool calls of a round sequentially, but the
401
+ agent-returning ones (the delegations produced by `ask` and
402
+ `hand_off_to_*`) are asked **in parallel** afterwards (`Open.traverse`,
403
+ `cpus > 1`). A specialist conversation is a persisted save file with
404
+ persistence locks behind it (`Open.sensible_write` → `Open.lock` on the
405
+ save file), so two delegations of one round that target the same
406
+ conversation would drive that conversation twice at the same time and the
407
+ process used to block forever on the lock.
408
+
409
+ The fix lives at the execution boundary, immediately before
410
+ `Open.traverse`: `LLM.process_calls` collects the `save_file` of every
411
+ pending delegation and, when two share one, converts the round into an
412
+ error round for the delegations instead of raising:
413
+
414
+ - `save_file` is the conversation's **actual persistence target**, so it is
415
+ the correct identity for this invariant: two delegations sharing a save
416
+ file contend for the same storage even when their logical names differ,
417
+ and delegations with the same name cannot share one.
418
+ - The check runs **after** the tool calls of the round (so it sees every
419
+ delegation the model staged) and **before** any `agent.chat`
420
+ executes, so a conflicted batch never starts a specialist.
421
+ - Every agent-returning entry of `tool_call_content` is replaced by one
422
+ `ScoutException` (same message, naming the conflicting save files). The
423
+ existing `Exception` branch of the result loop then turns each into a
424
+ normal `error` `function_call_output`, paired to its own call id, so
425
+ the model receives the failure as tool output and can rethink the plan.
426
+ Rejection is batch-wide by design: the agent sub-batch is either valid
427
+ as a whole or not started at all.
428
+ - Non-delegation tool calls of the round keep their real results — the
429
+ failure belongs to the delegation batch, not to the round. (This is not
430
+ transactional: side effects already performed by earlier tool calls
431
+ stand.)
432
+ - Staged prompts are rolled back in memory: delegation preparation appends
433
+ one user prompt per delegation (plus one `clear_tools` marker when
434
+ applicable) to the conversation's chat before dispatch. Those appends
435
+ happen in memory only — no save occurs until `Agent#chat` — so the
436
+ conflicted batch pops them again, walking the round's calls newest
437
+ first and removing each staged tail (a `clear_tools` marker immediately
438
+ before a staged prompt belongs to that same staging). A corrected round
439
+ afterwards therefore finds each conversation exactly as it was before
440
+ the faulty one.
441
+ - A restarting delegation is un-restarted first, not merely popped:
442
+ `hand_off`'s `new_conversation` and `ask_conversation`'s `restart:` do
443
+ more than append — `Agent#start` **re-branches the conversation in
444
+ place** before the prompt is staged (start_chat kept, every
445
+ accumulated turn dropped) and writes a snapshot under
446
+ `<save_file>.files/resets/`. So `Agent#start` now stashes the exact
447
+ displaced chat object (`restart_undo_stash`, one restart deep), and the
448
+ conflicted batch pops the staged prompt off the restart branch and
449
+ swaps the displaced chat back (`restore_restarted_chat`, which refuses
450
+ if the restart branch has advanced). The `resets/` snapshot needs no
451
+ compensating action: it is an append-only recovery record, never read
452
+ back by the live conversation. The same identity gap applies here in
453
+ reverse — the preflight detects save-file conflicts, but the undo
454
+ walks agent objects; both agree because `ask_conversation` memoizes
455
+ **one holder per `<specialist>/<conversation>` key**, so every
456
+ delegation of a conversation mutates the same in-memory chat, and the
457
+ exact-restore regression test asserts the full message list around a
458
+ three-delegation mixed batch (plain, `clear_tools`, restart) through
459
+ that single shared holder.
460
+ - Delegations without a `save_file` (persist-less ephemeral agents, mock
461
+ workers) are compacted out of the comparison, exactly as their null
462
+ paths cannot contend for storage.
463
+
464
+ Omitting the conversation name routes both delegations to the `default`
465
+ slot of the same specialist, so two anonymous delegations to one worker
466
+ share one save file and conflict exactly like two explicit ones. An
467
+ `ask` names its conversation directly, while a `hand_off_to_Worker` slot
468
+ asks the conversation named after its slot (`Worker/Worker`); both
469
+ resolve onto the same conversation holder, so a `hand_off_to_Worker` and
470
+ an `ask(..., conversation: 'Worker')` of one round conflict as well. The
471
+ slot keeps whatever case the registration used — nothing lower-cases it.
472
+
473
+ Known scope: delegations issued from **independent rounds or processes**
474
+ can still contend for the same conversation and wait on the persistence
475
+ lock. That is the historical locking behavior and is not addressed here.
476
+
477
+ ---
478
+
220
479
  ### Delegated inference receipts
221
480
 
222
481
  When a delegation tool returns an `LLM::Agent`, `LLM.process_calls` embeds
223
482
  the child agent's `meta` messages in the parent `function_call_output`
224
483
  envelope under the `meta` key, as an Array of **already-deserialized** field
225
484
  Hashes (one for the child's own inference metadata, one per producer
226
- reference). These receipts are provenance evidence, not parent-chat
485
+ reference: a `job` key holding the child job path). These receipts are provenance evidence, not parent-chat
227
486
  messages: the child's inference metadata and producer job reference are read
228
487
  from the paired tool output and never injected into the parent chat. Provenance
229
488
  tooling consumes them through `Chat.agent_meta_evidence` and the `:agent_job`
230
489
  relation; see [Provenance.md](Provenance.md) for the extraction, precedence
231
- (current `meta` over legacy `agent_meta`), and accounting rules.
490
+ (the `meta` key only; the legacy `agent_meta` envelope is no longer read), and accounting rules.
232
491
 
233
492
  ---
234
493
 
@@ -245,7 +504,7 @@ call time — it is hard-coded at registration time.
245
504
  | Parameter | Description |
246
505
  |---|---|
247
506
  | `agent` | A pre-loaded `LLM::Agent` instance. |
248
- | `name` | Tool name suffix (e.g., `worker` → `hand_off_to_worker`). |
507
+ | `name` | Tool name suffix (e.g., `Worker` → `hand_off_to_Worker`), and the conversation the slot asks. |
249
508
  | `description` | Tool description for the LLM. |
250
509
  | `&block` | Optional custom tool block. Defaults to: `agent.user(message); agent.chat`. |
251
510
 
@@ -260,6 +519,18 @@ call time — it is hard-coded at registration time.
260
519
 
261
520
  ---
262
521
 
522
+ ## Known drift
523
+
524
+ - **`inherit: 'tools'` is chat-scoped, not task-scoped.** The implementation
525
+ reads `self.current_chat.tooling`, i.e. the tooling of the caller's *whole*
526
+ current chat — which is what [user/Delegation.md](../user/Delegation.md)
527
+ now documents. A commented-out alternative (`social_caller_context.tooling`)
528
+ in the source shows caller-delta (task) scoping was the original intent.
529
+ Pin the intended semantics with a regression test before changing either
530
+ side.
531
+
532
+ ---
533
+
263
534
  ## Legacy parameter handling
264
535
 
265
536
  The old `chat` parameter is silently accepted for backward compatibility via
@@ -283,6 +554,21 @@ New code should use `conversation` and `inherit` as separate parameters.
283
554
  | `lib/scout/llm/agent.rb` | `Agent` class, `ask` entry point, `load_agent` class method |
284
555
  | `lib/scout/llm/agent/chat.rb` | `start_chat`, `current_chat`, Chat proxy via `method_missing` |
285
556
  | `lib/scout/llm/agent/workflow.rb` | `chat_task`, `log_agent` — workflow integration |
557
+ | `lib/scout/llm/chat/provenance.rb` | Live passes over save files, society trees and `.jobs` sidecars |
558
+ | `lib/scout/llm/tools/call.rb` | `<base>.jobs` writer/removal, sequential tool-call dispatch, parallel delegation preflight and `Open.traverse` execution |
559
+
560
+ ## Tests
561
+
562
+ | Behavior documented above | Test anchor |
563
+ |---|---|
564
+ | `open_conversation` pipeline (template memoization, seed, anchor, restart, validation) | `test/scout/llm/agent/test_conversation.rb` — `test_open_conversation_uses_the_memoized_template_but_returns_new_agents`, `test_shared_construction_clones_seed_and_options_and_anchors_before_start`, `test_open_conversation_defaults`, `test_open_conversation_scopes_identity_per_conversation`, `test_open_conversation_restart_rebranches_existing_conversation`, `test_open_conversation_validation`, `test_ask_conversation_prompt_is_never_parsed_as_chat_syntax` |
565
+ | `inherit` modes and preamble ordering | `test/scout/llm/agent/test_conversation.rb` — `test_open_conversation_inherit_none_tools_conversation`, `test_open_conversation_preamble_follows_inherited_context` |
566
+ | `clear_tools` mode: continuation marker, creation/restart fallback, context-only clearing, repeated markers, validation | `test/scout/llm/agent/test_conversation.rb` — `test_ask_conversation_clear_tools_continuation_after_conversation_seed`, `test_ask_conversation_clear_tools_continuation_after_none_seed`, `test_ask_conversation_clear_tools_creation_seeds_like_conversation`, `test_ask_conversation_clear_tools_restart_takes_the_fallback`, `test_ask_conversation_clear_tools_repeated_markers_equivalent`, `test_clear_tools_is_a_valid_inherit_mode` |
567
+ | `adopt: :current` seeding | `test/scout/llm/agent/test_delegate.rb` — `test_adopt_current_folds_template_progress_into_the_seed`, `test_adopt_with_empty_template_current_chat_is_a_no_op` |
568
+ | `delegate` hand-off block, slot naming, parent sweep | `test/scout/llm/agent/test_delegate.rb` — `test_default_block_returns_an_agent`, `test_parent_save_sweeps_the_hand_off_child`, `test_hyphenated_name_gives_a_sanitized_slot`, `test_pre_registered_agent_is_the_society_template`, `test_custom_block_receives_the_passed_agent_and_mutates_it`, `test_bad_hand_off_returns_the_exception_not_a_raise` |
569
+ | Society persistence layout and autosave | `test/scout/llm/agent/test_save.rb` — `test_society_dir_for`, `test_save_nested_society`, `test_save_cyclic_society_terminates`, `test_child_auto_save_keeps_canonical_layout`, `test_restart_snapshot`, `test_save_produces_no_legacy_log_tree` |
570
+ | Legacy `chat` parameter mapping | no direct test (`social_tool_parameters`, `lib/scout/llm/agent/conversation.rb`); the compatibility path is exercised only indirectly through stored-call replay. |
571
+ | Parallel delegation preflight: save-file conflicts (default and named slots), mixed `ask`/`hand_off` batches, error results instead of an abort, staged-prompt rollback, restart undo (`new_conversation`/`restart:` exact-restore through the shared holder), side-effect tool results kept, hang regression | `test/scout/llm/tools/test_call_delegation_conflict.rb` |
286
572
 
287
573
  ---
288
574
 
@@ -291,5 +577,5 @@ New code should use `conversation` and `inherit` as separate parameters.
291
577
  - [../user/Delegation.md](../user/Delegation.md) — User guide to delegation.
292
578
  - [Provenance.md](Provenance.md) — Receipt-based provenance for delegated inference.
293
579
  - [../user/MultiAgentWorkflows.md](../user/MultiAgentWorkflows.md) — Orchestration patterns.
294
- - [../../research/agent-delegation-analysis.md](../../research/agent-delegation-analysis.md) — Deep investigation.
295
- - [../../research/multi-agent-patterns-analysis.md](../../research/multi-agent-patterns-analysis.md) — SC26 patterns.
580
+ - [../../research/subsys/agent-delegation.md](../../research/subsys/agent-delegation.md) — Probe-verified delegation/subagent study.
581
+ - [../../research/subsys/agent-society.md](../../research/subsys/agent-society.md) — Probe-verified agent-directory/society study.