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
@@ -0,0 +1,201 @@
1
+ # 03 - Agent class and delegation semantics
2
+
3
+ > Investigation, not normative documentation. Verified behavior of the
4
+ > `LLM::Agent` class, its lifecycle, structured output, socialization and
5
+ > delegation. Normative reference: `doc/user/BuildingAgents.md`,
6
+ > `doc/developer/DelegationInternals.md`, `doc/user/Delegation.md`.
7
+
8
+ ## Scope
9
+
10
+ `lib/scout/llm/agent.rb` plus `agent/{chat,iterate,delegate,conversation,attach,save}.rb`.
11
+ Job binding (`AgentWorkflow`) is covered by
12
+ `research/subsys/agentworkflow.md`; agent directory resolution and the society
13
+ save tree by `research/subsys/agent-society.md`.
14
+
15
+ ## Verified behavior
16
+
17
+ ### Class surface
18
+
19
+ `Agent` is a stateful wrapper over a Chat:
20
+
21
+ - Construction: `Agent.new(workflow:, knowledge_base:, start_chat:, **kwargs)` -
22
+ extra kwargs land in `other_options`.
23
+ - Conversation state: `start_chat` (lazily `Chat.setup([])`), `current_chat`
24
+ (lazily `= start_chat`), `chats`, `society`; unknown message-like methods
25
+ are forwarded to `current_chat` through `method_missing`.
26
+ - Rounds: `chat(options = {})` appends the assistant message(s) and
27
+ auto-saves; bare `ask(messages = nil, options = {})` performs a round via
28
+ `LLM.ask` with **no** auto-save.
29
+ - `start(chat = nil)` re-branches: `current_chat = start_chat.follow(chat)` -
30
+ a fresh branch object seeded by `start_chat` plus the optional chat.
31
+ - `prompt` parses its String argument as Scout chat-file syntax (role-looking
32
+ lines become real roles); `user` appends one literal user message. This is
33
+ precisely why delegated prompts must be built with `user`.
34
+ - Structured output: `json` (retries once with a system message asking for
35
+ bare JSON on parse failure), `json_format(format, options)` (appends the
36
+ `option format <json-schema>` message and sets the chat option),
37
+ `iterate(prompt, &block)`.
38
+ - Persistence: `save_file`, `save(path = nil)`, per-round auto-save in `chat`,
39
+ restart snapshots in `start`.
40
+
41
+ ### `iterate`
42
+
43
+ Forces `endpoint :responses`, appends the prompt, sets a
44
+ dictionary-of-strings JSON schema via `json_format`, sets
45
+ `option :format, :text`, then `TSV.traverse dict, **kwargs, &block` - the
46
+ dictionary entries are streamed to the block as items.
47
+
48
+ ### Delegation mechanics
49
+
50
+ `socialize(options = {})` installs a narrow `ask` tool. Parameters (all
51
+ required only `agent` and `prompt`): `agent`, `prompt`, `conversation`
52
+ (pattern `^[A-Za-z0-9][A-Za-z0-9_.-]*$`), `inherit` (enum
53
+ `SOCIAL_INHERIT_MODES` = `none/tools/conversation/clear_tools`, default
54
+ `tools`; `clear_tools` also acts on continuation, see
55
+ `research/clear-tools-inherit.md`). The tool
56
+ block never receives the specialist Chat object; it calls `ask_agent` ->
57
+ `ask_conversation` -> `open_conversation` + `agent.user(prompt)`.
58
+
59
+ `delegate(agent, name, description, task_name = nil, &block)` registers the
60
+ `hand_off_to_<name>` tool (or `task_name`). For an `LLM::Agent` target it
61
+ pre-registers `@society[name] ||= agent` (the template cache) and the default
62
+ block calls
63
+
64
+ ```
65
+ ask_conversation(name, message,
66
+ conversation: sanitized_slot(name), inherit: 'none',
67
+ template: agent, adopt: :current, restart: new_conversation)
68
+ ```
69
+
70
+ Duck-typed targets keep the legacy direct mutation (`agent.start if
71
+ new_conversation; agent.user message; agent`).
72
+
73
+ `open_conversation(name, conversation: 'default', inherit: 'tools',
74
+ options: {}, preamble:, anchor:, restart:, template:, adopt:, job:)`:
75
+
76
+ 1. Normalize name/conversation/inherit/adopt. Name pattern
77
+ `SOCIAL_AGENT_NAME = /\A[a-z_.-]+\z/i`, conversation pattern
78
+ `SOCIAL_CONVERSATION_NAME = /\A[a-z0-9][a-z0-9_.-]*\z/i`; invalid values
79
+ raise `ParameterException`.
80
+ 2. `key = social_chat_key(name, conversation)` = `"Name/conversation"`. An
81
+ existing key returns the **same** agent object (identity per key; the
82
+ `inherit` argument is ignored). `restart: true` re-branches in place -
83
+ the same object, the chat reset to the seeded prefix.
84
+ 3. A new conversation: `start_social_chat` clones the template
85
+ (`clone_social_agent`: fresh `start_chat`/`other_options` copies,
86
+ `society = nil`, `chats = nil`, `current_chat = nil`); the initial chat is
87
+ `copy(template.start_chat)` + (`adopt: :current` -> the template's progress
88
+ delta) + the inherited context + the preamble; then `agent.start(initial_chat)`;
89
+ `save_file = anchor || society_save_file(name, conversation)`; and
90
+ `@chats[key] ||= agent`.
91
+ 4. `job:` is accepted and ignored (reserved).
92
+
93
+ Inherit semantics:
94
+
95
+ - `none` -> empty Chat.
96
+ - `tools` -> `self.current_chat.tooling` (the `introduce`/`tool`/`mcp`/`kb`
97
+ roles). Note the code uses the *whole current chat's* tooling, not the
98
+ caller task's - see the mismatch below.
99
+ - `conversation` -> `social_caller_context` = `social_context_delta(self)` =
100
+ `current_chat` minus `start_chat` (by object identity when the start-chat
101
+ messages are shared Hash objects, else longest-common-prefix drop).
102
+
103
+ `social_context_delta` implements one rule for both directions (caller
104
+ context and `adopt: :current` template progress): identity-set match against
105
+ `start_chat`, with common-prefix fallback.
106
+
107
+ Option propagation: `social_agent_options(options)` = deep-dup of
108
+ `other_options` merged with the supplied options, minus
109
+ `SOCIAL_PRIVATE_OPTIONS` (`agent, client, current_meta, format, messages,
110
+ no_ask_override, previous_response_id, process, return_messages, tool_choice,
111
+ tools`). Specialists therefore never inherit the caller's tools or format by
112
+ accident; `endpoint`/`model` style options do flow.
113
+
114
+ ### Agent-round fan-out
115
+
116
+ `LLM.process_calls` (tools/call.rb:140-193) collects tool results that are
117
+ `LLM::Agent` and fans them out with `Open.traverse cpus:` (config
118
+ `:cpus,:agent_ask,:agents`, env `ASK_AGENTS`, default 3), calling
119
+ `agent.chat(return_messages: true)`. Each answer is paired with its own call
120
+ **by tool-call position** (the n-th agent-returning call consumes the n-th
121
+ answer) - this avoids the first-occurrence bug with duplicate agents. A
122
+ `.jobs` sidecar of in-flight workflow job short paths is written per round
123
+ and removed in `ensure`.
124
+
125
+ ### Attachments
126
+
127
+ `Agent#attachments` registers a single `attach` Proc tool with properties
128
+ `file` (string, required) and `file_type` (enum `ATACH_TYPES` =
129
+ `auto image pdf png jpeg`, default `auto`). Current behavior (fixed
130
+ 2026-09-11, uncommitted): `file_type` defaults to `auto`; only `auto` is
131
+ normalized (pdf by lowercase `.pdf` extension, else `image`); the dispatcher
132
+ is `case file_type` with a subject, so `image`/`png`/`jpeg` route to
133
+ `self.image(path)`, `pdf` routes to `self.pdf(path)`, and an unknown type
134
+ raises `ScoutException` (returned as the tool error). Before the fix the
135
+ normalization overwrote every explicit type to `image` and the dispatcher was
136
+ a bare `case`, so the pdf branch was unreachable (finding F1, fixed with
137
+ `test/scout/llm/agent/test_attach.rb`, 8/0). Only `.pdf` is sniffed under
138
+ `auto`: a PDF with another extension still needs an explicit
139
+ `file_type: 'pdf'`.
140
+
141
+ ## Sharp edges and known issues
142
+
143
+ - **`inherit: 'tools'` scope drift** (F17, open). `doc/developer/DelegationInternals.md`
144
+ says it copies "caller's task chat tooling"; the code copies
145
+ `self.current_chat.tooling` (the whole current chat, which for a
146
+ mid-conversation agent may include tooling added after start). The
147
+ commented-out `social_caller_context.tooling` line in conversation.rb:256-266
148
+ shows the intent drifted. Contained by `SOCIAL_PRIVATE_OPTIONS`, but real.
149
+ - **Fixed 2026-09-11, uncommitted:** F1 `attach` never attached PDFs
150
+ (normalization overwrite + bare-`case` always matching the image branch);
151
+ now normalized to `auto`-only with a subject-form dispatcher.
152
+ - `ATACH_TYPES` typo (should be `ATTACH_TYPES`) and the
153
+ `ScoutException "Unkown file type"` message typo remain, deliberately -
154
+ renaming a constant is API-visible.
155
+ - `open_conversation(job:)` is accepted and ignored.
156
+ - The `LLM.process_calls` cpus knobs (`:agent_ask`, `:agents`, env
157
+ `ASK_AGENTS`) and the `.jobs` sidecar lifecycle are documented only in code
158
+ comments; `doc/user/MultiAgentWorkflows.md` does not mention them.
159
+ - Restart snapshots (`.files/resets/<timestamp>.chat`) are written lazily -
160
+ nothing to snapshot means no `resets` directory. The collision-suffix rule
161
+ was read but not probed.
162
+
163
+ ## Open questions
164
+
165
+ - Whether `inherit: 'tools'` should be caller-task-scoped (docs) or
166
+ whole-current-chat-scoped (code); a regression test pinning the intended
167
+ semantics would help. See `research/subsys/agentworkflow.md` for the
168
+ `tooling` helper's role.
169
+ - Probing constraint worth knowing when reproducing: a probe that requires
170
+ scout-ai inside a forked worker must pin the checkout lib via
171
+ `RUBYLIB`/`-I` **and** pass explicit `backend:`/`endpoint:` in each Agent's
172
+ own options - `Scout::Config` pinning does not survive the forked
173
+ `Open.traverse` workers, and host `Scout.etc` endpoint files otherwise leak
174
+ in. Recorded as the Cortex probe artifact `probe/subprocess_exec_in_property.rb`.
175
+
176
+ ## Evidence
177
+
178
+ Provenance: derived from the 2026-09-10/11 Cortex subsystem studies, probed
179
+ against this checkout at HEAD `a992a33` plus the uncommitted 2026-09-11 fix
180
+ sweep. The attach fix (F1) in that sweep is the only change in scope here;
181
+ described above as current behavior.
182
+
183
+ - Code: `lib/scout/llm/agent.rb:15-21` (construction), `:85-88` (`job=` meta
184
+ at dispatch), `:100-140` (ask/tool assembly, `process_exception`),
185
+ `:159-163` (`prompt` vs `user`), `:174-228` (`load_agent`);
186
+ `agent/chat.rb:1-6,33-61,62-90`; `agent/iterate.rb:7-42`;
187
+ `agent/delegate.rb`; `agent/conversation.rb:4-12` (constants), `:44-62`
188
+ (`open_conversation`), `:107` (name validation), `:174-195`
189
+ (`social_agent_options`), `:235-266` (`social_context_delta`, inherit);
190
+ `agent/attach.rb:4,14-35,44-52`; `agent/save.rb`;
191
+ `lib/scout/llm/tools/call.rb:140-193`.
192
+ - Tests: `test/scout/llm/agent/{test_attach,test_chat,test_conversation,
193
+ test_delegate,test_save,test_workflow}.rb`; `test/scout/llm/test_agent.rb`.
194
+ - Probe receipts: Cortex probe artifact `probe/scout_agent_delegation_api.rb`
195
+ (Observation `scout_agent_delegation_api`), run through the
196
+ `Observation/probe` property; its JSON output covers ask/chat auto-save,
197
+ json/iterate, the inherit-mode role sets, `open_conversation` identity and
198
+ restart, delegate clone/template semantics, the `ask` tool schema
199
+ (parameters `[agent, conversation, inherit, prompt]`, inherit enum with
200
+ default `tools`, conversation pattern), `process_calls` answer pairing and
201
+ the society save layout.
@@ -0,0 +1,275 @@
1
+ # 10 - Agent directories and the society harness
2
+
3
+ > Investigation, not normative documentation. Verified behavior of the
4
+ > `Agent/<Name>` directory convention, `load_agent` resolution, the runtime
5
+ > society, the on-disk `society/` save tree, chat-level references between
6
+ > agents and the CLI harness. Normative reference:
7
+ > `doc/user/BuildingAgents.md`, `doc/developer/DelegationInternals.md`,
8
+ > `doc/developer/Architecture.md`.
9
+
10
+ ## Scope
11
+
12
+ The `Agent/<Name>/{start_chat,workflow.rb,agent.rb,knowledge_base,python}`
13
+ convention, `LLM::Agent.load_agent` resolution mechanics, the runtime
14
+ `@society`/`@chats` state, the on-disk `society/` save tree, chat-level
15
+ `import:` references and the `agent ask|find|kb` CLI. Agent class semantics
16
+ are owned by `research/subsys/agent-delegation.md`; the `AgentWorkflow`
17
+ mixin by `research/subsys/agentworkflow.md`.
18
+
19
+ ## Verified behavior
20
+
21
+ ### What a named agent is on disk
22
+
23
+ A named agent is a directory whose *name* is resolvable through Scout path
24
+ maps. **There is no manifest, no roster file and no declaration step.** A
25
+ directory may contain any of:
26
+
27
+ | entry | effect at load time |
28
+ |---|---|
29
+ | `start_chat` (also `start_chat.chat`) | chat file -> `agent.start_chat` seed (system prompt, options, `tool:`/`introduce:`/`kb:`/`mcp:` roles) |
30
+ | `workflow.rb` | Scout workflow -> tools via `LLM.workflow_tools`; also the fallback `introduce` seed when no `start_chat` exists |
31
+ | `agent.rb` | Ruby file whose last expression must be an `LLM::Agent` (Kernel `load`ed) |
32
+ | `knowledge_base/` | `KnowledgeBase.load` if it exists |
33
+ | `python/` with `*.py` | `PythonWorkflow.load_directory dir, 'ScoutAgent'` -> workflow |
34
+ | `workflow.md` / `README.md` | never read by the agent loader; only `Workflow#documentation` reads them from a workflow's own libdir |
35
+
36
+ Details:
37
+
38
+ - `start_chat` wins over `start_chat.chat`; if only `start_chat.chat` exists
39
+ the seed is **empty** (see the sharp edges below).
40
+ - `agent.rb` and `workflow.rb` in the same directory: `agent.rb` is used for
41
+ the agent *object*, and it must itself return an Agent - a plain
42
+ `agent.rb` that does not ends in an Agent raises `NoMethodError`.
43
+ - Deep nested names work (`Agent/Deep/Nested/start_chat` loads as agent name
44
+ `'Deep/Nested'`); snake/lowercase names work; Symbols are accepted.
45
+
46
+ ### `load_agent` resolution algorithm
47
+
48
+ `lib/scout/llm/agent.rb:174-228`:
49
+
50
+ 1. A Symbol name is stringified.
51
+ 2. **Filename branch** (`Path.is_filename?(agent_name)` - a string without
52
+ newlines that *exists on disk*; note this is `File.exist?`, not
53
+ `Open.exists?`, so remote names never enter this branch):
54
+ - a directory with `agent.rb` -> `load dir.agent.rb`;
55
+ - any other existing file -> `load agent_name`;
56
+ - an existing directory *without* `agent.rb` falls through to the named
57
+ branch with the full path as the "name" - typically
58
+ `No agent found with name <path>`.
59
+ 3. **Named branch** - candidates, each tried only when the previous
60
+ `.exists?` is false: `Scout.workflows[name]`, `Scout.Agent[name]`,
61
+ `Scout.var.Agent[name]`, `Scout.chats.Agent[name]`, `Scout.chats[name]`.
62
+ These are user-map lookups (`~/.scout/...`), but Scout pathmap resolution
63
+ still applies the `current` map, which is how `Agent/<name>` in a repo
64
+ root is found; after `Dir.chdir` a previously resolvable PWD agent is no
65
+ longer found (resolution is PWD-at-call-time).
66
+ Ordering nuance: the *workflow* candidate is checked first, and when
67
+ `Scout.workflows[name]` exists it wins for the workflow and
68
+ `agent_path = workflow_path`, so `start_chat`/`knowledge_base` are then
69
+ looked up inside the workflow checkout.
70
+ 4. `raise ScoutException, "No agent found with name #{agent_name}"` unless
71
+ `workflow_path.exists? || agent_path.exists?`.
72
+ 5. Workflow selection (first match): `Workflow.require_workflow(name)` when
73
+ `Scout.workflows[name]` exists (the autoinstall/git-clone branch - it can
74
+ hang a probe through the `TryAgain` retry loop); else
75
+ `Workflow.require_workflow_file(agent_path.workflow.rb)` when present;
76
+ else `PythonWorkflow.load_directory(agent_path.python, 'ScoutAgent')`
77
+ when `python/*.py` exist; else the workflow stays nil (start_chat-only
78
+ agent).
79
+ 6. Knowledge base: `agent_path.knowledge_base` else
80
+ `workflow_path.knowledge_base`.
81
+ 7. start_chat: `agent_path.start_chat` else `workflow_path.start_chat` else -
82
+ when a workflow exists and `workflow.documentation[:description]` is
83
+ non-empty - `[{role: 'introduce', content: workflow.name}]`; else empty.
84
+ 8. `LLM::Agent.new(**options.merge(workflow:, knowledge_base:, start_chat:))`
85
+ and `agent.path = agent_path.find` (used by `scout agent find`).
86
+
87
+ `doc/user/BuildingAgents.md`'s discovery list matches steps 3.1-3.5; it
88
+ omits the filename branch entirely and the workflow-checkout redirect.
89
+
90
+ ### Caching and module identity
91
+
92
+ - `@@agent_workflow ||= {}` caches **workflows** per name - a class variable
93
+ shared across all callers. Two different directories defining the same
94
+ module name yield the **same** module object (first definition wins; the
95
+ second `require_workflow_file` does not redefine it). Editing
96
+ `workflow.rb` mid-process does not invalidate the cache. The module is
97
+ shared across agent *templates* too.
98
+ - The **Agent object is not cached**: `load_agent` returns a fresh Agent each
99
+ call. The per-name template identity that matters at runtime is
100
+ `@society[name]` inside each parent (`@society[agent_name] ||=
101
+ load_agent(...)`) - one immutable template per specialist per parent,
102
+ cloned per conversation.
103
+ - `socialize` does not preload anything: `@society` stays empty until the
104
+ model actually calls `ask`.
105
+
106
+ ### Tooling provisioning
107
+
108
+ Nothing tool-related happens inside `load_agent`. Tools are assembled at
109
+ **ask time** in `Agent#ask`: `options[:tools]` merged with
110
+ `@other_options[:tools]` (where `socialize`'s `ask` tool and the
111
+ `hand_off_to_*` tools live), then `LLM.workflow_tools(workflow)` for a
112
+ workflow with tasks, then the KB tools.
113
+
114
+ The start_chat seed carries tool roles which the chat pipeline expands at
115
+ prepare time: `tool:` -> `Chat.load_workflow(name)` + one tool per task (or
116
+ a single task with input restriction); `introduce:` ->
117
+ `Workflow.require_workflow` + a `user`-role documentation block; `kb:` ->
118
+ `KnowledgeBase.load`, falling back to `LLM.load_agent(name).knowledge_base`.
119
+
120
+ `Chat.load_workflow` has its own resolution: a constant first, then
121
+ `Scout.chats.Agent[workflow]['workflow.rb']` (**only** the chats.Agent map),
122
+ then `Workflow.require_workflow`. So a `tool: Name` in a start_chat can
123
+ resolve against an agent directory even when `load_agent('Name')` would find
124
+ it elsewhere.
125
+
126
+ ### The runtime society
127
+
128
+ - `@society` (per parent): `name -> immutable template Agent`. `@chats`:
129
+ `"<name>/<conversation>" -> conversation holder`.
130
+ - Names are validated by `SOCIAL_AGENT_NAME = /\A[a-z_.-]+\z/i` in
131
+ `normalize_social_agent_name` (a bad name raises `ParameterException`);
132
+ conversations by `SOCIAL_CONVERSATION_NAME = /\A[a-z0-9][a-z0-9_.-]*\z/i`.
133
+ - Inheritance modes `none/tools/conversation` (plus `clear_tools`, the
134
+ continuation-time clearing mode — see `research/clear-tools-inherit.md`);
135
+ private options are stripped
136
+ by `SOCIAL_PRIVATE_OPTIONS` - only things like `endpoint`/`model` flow to
137
+ specialists.
138
+ - The roster is a **free string parameter**: the `ask` tool's `agent`
139
+ property is `{type: string, description: "Name of the specialist agent to
140
+ ask"}` with `required ["agent","prompt"]` - no enum, no schema-level
141
+ validation, no discovery of available specialists. Availability is decided
142
+ at call time by `load_agent(name)`; an unknown name surfaces as the
143
+ `ScoutException` returned as the tool result.
144
+ - **No "society import" or "specialization" feature exists in the code.**
145
+ Those words appear only in unmaintained research notes describing another
146
+ repository's conventions. The closest real mechanism is N sibling agent
147
+ directories plus `import:`/`tool:`/`introduce:` chat-file references and
148
+ an orchestrator that `socialize`s.
149
+
150
+ ### Chat-level references between agents
151
+
152
+ - `import:` (and `continue:`/`last:`) roles are expanded by `Chat.imports`
153
+ via `find_file`, which resolves in order: relative to the importing chat's
154
+ directory, the caller's libdir, the literal path, a remote URL, then
155
+ `Scout.chats[file]`.
156
+ - `Chat#import(file)` just appends `{role: 'import', content: file}`; the
157
+ expansion happens later in the pipeline.
158
+ - A `main.chat` with `import: other.chat` expands into the other chat's
159
+ messages inline, resolved relative to `main.chat`. This is how one agent's
160
+ start_chat can absorb another agent's chat file, including its
161
+ `tool:`/`introduce:` declarations - the practical "society import".
162
+
163
+ ### The on-disk `society/` tree
164
+
165
+ - `Agent::SOCIETY_DIR = 'society'`, `SOCIETY_CHAT_FILE = 'agent.chat'`,
166
+ `SAVE_DEPTH_LIMIT = 32`.
167
+ - Root rule `society_dir_for(chat_path)`: `<name>.chat` -> sibling
168
+ `<name>.society`. Nested rule `society_dir(path)`: a chat already inside a
169
+ society tree (`nested_save?` - exactly three directory levels up named
170
+ `society` or `*.society`) keeps a plain `society` sibling.
171
+ - `canonical_chat_file(files_dir, name)` = `<files_dir>/<name || 'agent'>.chat`
172
+ - the single source of truth for `AgentWorkflow#log_agent`,
173
+ `scout agent ask` and `llm ask --chat`.
174
+ - A parent with one open child conversation saves `root.chat` plus
175
+ `root.society/Child/work_1/agent.chat`, matching the documented layout.
176
+ `Agent#save` assigns a save_file to every reachable child so later turns
177
+ auto-save in place.
178
+ - The society tree is *scanned* by provenance (`society_dir_of`,
179
+ `society_agent_chats` - bounded scan, depth limit 128, `agent.chat` files
180
+ only, no symlinks - and `society_live`). `Chat.society_dir_of` delegates
181
+ to the Agent rules when the class is loaded and mirrors save.rb otherwise.
182
+ - Provenance deliberately treats society chats as independent recovery
183
+ artifacts, not logs (`DIRECT_LOG_CHAT_GLOBS`).
184
+
185
+ ### CLI harness
186
+
187
+ - `scout_commands/agent/ask` - `LLM::Agent.load_agent(agent_name)` with
188
+ ARGV[0] the agent name; endpoint/model overrides; `-t` template (resolved
189
+ against `Scout.questions`, `Scout.chats.system`, `Scout.chats`);
190
+ `-c` chat (follow + `save_file = canonical_chat_file(chat + '.files',
191
+ agent_name)` -> auto-append to the chat file); `-w` extra workflow tool;
192
+ `-i` imports; `-f` files; inline `# ask:` rewriting in files.
193
+ - `scout_commands/agent/find` - loads the agent and prints `agent.path`.
194
+ - `scout_commands/agent/kb` - `agent_dir = Scout.var.Agent[agent]` **only**
195
+ (not the five-way lookup), then delegates to `scout kb` with
196
+ `--knowledge_base <dir>`.
197
+
198
+ ## Sharp edges and known issues
199
+
200
+ - **`start_chat.chat` is silently ignored when `start_chat` exists, and
201
+ yields an empty seed when alone** (F19, open): `find_with_extension`
202
+ returns the missing literal `start_chat` path, and `LLM.chat(path)` then
203
+ reads a missing file silently - a silent misconfiguration.
204
+ - **The `@@agent_workflow` cache is process-global, shared and never
205
+ invalidated** (F19, open): first module definition wins; `workflow.rb`
206
+ edits are invisible until restart; two directories with the same module
207
+ name share the first module.
208
+ - **`scout agent kb` hard-codes `Scout.var.Agent[agent]`** (F16, open): one
209
+ of the five lookup roots, so agents living in `Scout.Agent` or
210
+ `Scout.chats.Agent` are unreachable; and `Chat.load_workflow` (`tool:`
211
+ roles) uses only `Scout.chats.Agent`, diverging from `load_agent`'s five
212
+ roots for the same name.
213
+ - **`agent.rb` undocumented in user docs** (open): the Kernel-`load` branch
214
+ and its "last expression must be an Agent" contract appear only in
215
+ Architecture.md's table.
216
+ - **Workflow-only agents do not always get an `introduce` seed** (open): the
217
+ seed comes only from `workflow.documentation[:description]`; a
218
+ `workflow.rb` with task descriptions but no workflow-level description
219
+ yields no seed - and `description 'x'` inside a module body raises
220
+ `ArgumentError` because `Workflow#description` is an accessor, not a DSL
221
+ setter.
222
+ - **`Path.is_filename?` requires existence** (open): a non-existing absolute
223
+ path is silently treated as a *name*, so
224
+ `load_agent('/abs/path/that/does/not/exist')` fails with
225
+ `No agent found with name /abs/...` - a confusing error message.
226
+ - `agent.path` is set only in the named branch; filename-branch agents have
227
+ `path == nil` (`scout agent find` prints nothing useful for them).
228
+ - `load_from_path` exists but is dead code in the repo - no caller in lib/,
229
+ test/ or scout_commands/.
230
+ - Architecture.md's require list for `agent.rb` is stale (it omits
231
+ `conversation`, `attach`, `save`).
232
+ - The third `elsif` in the `start_chat` lookup (agent.rb:219-224) is an
233
+ unreachable cosmetic dead branch.
234
+ - Python agents: the `python/` branch requires `python/*.py`;
235
+ `PythonWorkflow.load_directory` shells out to the gem's own python env and
236
+ could not be executed in the study environment - mechanism code-confirmed,
237
+ not execution-verified.
238
+
239
+ ## Open questions
240
+
241
+ - Does anything (ChatAnalyst, SC26-style suites) rely on
242
+ `Agent/<Name>` being found via `Scout.chats.Agent` specifically, given
243
+ `Chat.load_workflow` uses only that root for `tool:` roles? A silent
244
+ divergence between `load_agent` and `Chat.load_workflow` for the same name
245
+ is possible.
246
+ - Is there a supported way to reload an agent's workflow in-process (the
247
+ cache is never invalidated; tests use fresh processes)?
248
+ - Whether the filename-branch-vs-name behaviour for non-existing paths is
249
+ intended.
250
+
251
+ ## Evidence
252
+
253
+ Provenance: derived from the 2026-09-10/11 Cortex subsystem studies, probed
254
+ against this checkout at HEAD `a992a33` plus the uncommitted 2026-09-11 fix
255
+ sweep (attach/MCP/embed/torch); no fix in this sweep touches this subsystem.
256
+
257
+ - Code: `lib/scout/llm/agent.rb:160-238` (load_agent, requires);
258
+ `lib/scout/llm/agent/{conversation,delegate,save,workflow,chat}.rb`;
259
+ `lib/scout/llm/chat/process/{tools,files}.rb`;
260
+ `lib/scout/llm/chat/annotation.rb`;
261
+ `lib/scout/llm/chat/provenance.rb:1683-1810` (society scan);
262
+ `lib/scout/llm/tools/workflow.rb:79-94`;
263
+ `scout_commands/agent/{ask,find,kb}`; scout-essentials
264
+ `lib/scout/path/util.rb:8-15` (`is_filename?`); scout-gear
265
+ `lib/scout/workflow.rb`, `lib/scout/workflow/documentation.rb`.
266
+ - Probes (throwaway agent directories, no repo modifications, no LLM calls):
267
+ resolution order, error messages, caching and module identity,
268
+ `agent.rb` contract, `start_chat` extension precedence, mixed directories,
269
+ the doc-seed behaviour, `@@agent_workflow` sharing, tooling roles on
270
+ start_chat, nested/snake/symbol names, the PWD map and post-chdir
271
+ behaviour, `@society` templates and cloning, `chats` keys, name
272
+ normalization, `social_agent_options`, `Agent#import`, chat-file import
273
+ expansion, the society save tree, the `ask` tool schema. The import/save
274
+ probe is preserved as the Cortex probe artifact
275
+ `probe/agent_society_import.rb`.