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
@@ -0,0 +1,159 @@
1
+ require File.expand_path(__FILE__).sub(%r(/test/.*), '/test/test_helper.rb')
2
+ require 'scout/llm/agent'
3
+
4
+ class TestLLMChatSocietyView < Test::Unit::TestCase
5
+ def wfdir
6
+ @wfdir ||= begin
7
+ dir = Path.setup(Workflow.directory['society-view-wf'])
8
+ Workflow.directory = dir
9
+ dir
10
+ end
11
+ end
12
+
13
+ def root_chat
14
+ @root_chat ||= begin
15
+ sf = tmpdir['society-view'].find + '.chat'
16
+ Open.rm_rf(sf)
17
+ FileUtils.mkdir_p(File.dirname(sf))
18
+ FileUtils.touch(sf)
19
+ sf
20
+ end
21
+ end
22
+
23
+ def write_info(short_path, status, pid, type: 'string')
24
+ dir = wfdir[short_path].find
25
+ Open.rm_rf dir
26
+ FileUtils.mkdir_p(dir)
27
+ File.write(dir + '.info',
28
+ JSON.dump({status: status, pid: pid, type: type,
29
+ workflow: short_path.split('/').first,
30
+ task_name: short_path.split('/')[1]}))
31
+ dir
32
+ end
33
+
34
+ def write_child(agent, conversation, *messages)
35
+ dir = File.join(File.dirname(root_chat), File.basename(root_chat).sub(/\.chat\z/, '.society'), agent, conversation)
36
+ FileUtils.mkdir_p(dir)
37
+ file = File.join(dir, 'agent.chat')
38
+ Open.write(file, Chat.print(messages))
39
+ file
40
+ end
41
+
42
+ # ---------------------------------------------------------------
43
+ # Society dir derivation
44
+ # ---------------------------------------------------------------
45
+
46
+ def test_society_dir_of_root_save_file
47
+ assert_equal File.join(File.dirname(root_chat), 'society-view.society'),
48
+ Chat.society_dir_of(root_chat)
49
+ end
50
+
51
+ def test_society_dir_of_nested_child_matches_agent_rule
52
+ nested = File.join(File.dirname(root_chat), 'society-view.society', 'Worker', 'run', 'agent.chat')
53
+ assert_equal LLM::Agent.new.society_dir(nested),
54
+ Chat.society_dir_of(nested)
55
+ assert_equal File.join(File.dirname(root_chat), 'society-view.society', 'Worker', 'run', 'society'),
56
+ Chat.society_dir_of(nested)
57
+ end
58
+
59
+ def test_missing_society_dir_is_silent
60
+ assert_equal [], Chat.society_agent_chats(root_chat)
61
+ assert_equal [], Chat.society_live(root_chat, captured: [])
62
+ end
63
+
64
+ # ---------------------------------------------------------------
65
+ # Plain child: activity only (no job= meta ever written)
66
+ # ---------------------------------------------------------------
67
+
68
+ def test_active_plain_child_reports_agent_activity
69
+ write_child('Worker', 'run', {role: 'user', content: 'hi'})
70
+ entries = Chat.society_live(root_chat, captured: [])
71
+ assert_equal 1, entries.length
72
+ entry = entries.first
73
+ assert_equal :agent_activity, entry[:kind]
74
+ assert_equal 'Worker', entry[:agent]
75
+ assert_equal 'run', entry[:conversation]
76
+ assert_equal File.join('Worker', 'run', 'agent.chat'), entry[:relative]
77
+ assert_equal :dispatched, entry[:activity][:reason]
78
+ refute entry.key?(:job)
79
+ end
80
+
81
+ def test_tool_round_plain_child_reports_agent_activity
82
+ write_child('Worker', 'run',
83
+ {role: 'user', content: 'hi'},
84
+ {role: 'assistant', content: 'hm'},
85
+ {role: 'function_call', content: {name: 'slow', arguments: {}, id: 'c1'}.to_json})
86
+ entries = Chat.society_live(root_chat, captured: [])
87
+ assert_equal 1, entries.length
88
+ assert_equal :agent_activity, entries.first[:kind]
89
+ assert_equal :tool_round_in_flight, entries.first[:activity][:reason]
90
+ end
91
+
92
+ def test_finished_child_is_silent
93
+ write_child('Worker', 'run',
94
+ {role: 'user', content: 'hi'},
95
+ {role: 'assistant', content: 'bye'})
96
+ assert_equal [], Chat.society_live(root_chat, captured: [])
97
+ end
98
+
99
+ # ---------------------------------------------------------------
100
+ # Workflow-backed child: dangling job wins, activity still included
101
+ # ---------------------------------------------------------------
102
+
103
+ def test_workflow_child_with_running_job_reports_dangling_job
104
+ write_info('WF/ask/one', 'running', Process.pid, type: 'chat')
105
+ write_child('Worker', 'run',
106
+ {role: 'user', content: 'go'},
107
+ {role: 'meta', content: 'job=WF/ask/one'})
108
+ entries = Chat.society_live(root_chat, captured: [])
109
+ assert_equal 1, entries.length
110
+ entry = entries.first
111
+ assert_equal :dangling_job, entry[:kind]
112
+ assert_equal 'WF/ask/one', entry[:job]
113
+ assert_equal :running, entry[:state]
114
+ assert_equal 'Worker', entry[:agent]
115
+ # the activity hash is present even when the dangling job wins
116
+ assert_equal :dispatched, entry[:activity][:reason]
117
+ end
118
+
119
+ def test_captured_job_of_otherwise_finished_child_is_skipped
120
+ write_info('WF/ask/one', 'running', Process.pid, type: 'chat')
121
+ write_child('Worker', 'run',
122
+ {role: 'user', content: 'go'},
123
+ {role: 'meta', content: 'job=WF/ask/one'})
124
+ assert_equal [], Chat.society_live(root_chat, captured: ['WF/ask/one'])
125
+ end
126
+
127
+ def test_multiple_children_report_sorted_by_path
128
+ write_child('Zeta', 'run', {role: 'user', content: 'go'})
129
+ write_child('Alpha', 'later', {role: 'user', content: 'go'})
130
+ entries = Chat.society_live(root_chat, captured: [])
131
+ assert_equal %w(Alpha Zeta), entries.collect { |e| e[:agent] }
132
+ end
133
+
134
+ # ---------------------------------------------------------------
135
+ # Guards
136
+ # ---------------------------------------------------------------
137
+
138
+ def test_symlink_out_of_the_tree_is_not_followed
139
+ outer = tmpdir['outer-society'].find
140
+ FileUtils.mkdir_p(outer)
141
+ Open.write(File.join(outer, 'agent.chat'), Chat.print([{role: 'user', content: 'outside'}]))
142
+ link_dir = File.join(File.dirname(root_chat), 'society-view.society', 'Linked', 'run')
143
+ FileUtils.mkdir_p(link_dir)
144
+ File.symlink(outer, File.join(link_dir, 'agent.chat'))
145
+ entries = Chat.society_live(root_chat, captured: [])
146
+ assert_equal [], entries
147
+ end
148
+
149
+ def test_scan_depth_is_bounded
150
+ deep = File.dirname(root_chat)
151
+ 200.times do
152
+ deep = File.join(deep, 'society')
153
+ end
154
+ target = File.join(deep, 'a', 'b', 'agent.chat')
155
+ FileUtils.mkdir_p(File.dirname(target))
156
+ Open.write(target, Chat.print([{role: 'user', content: 'deep'}]))
157
+ assert_equal [], Chat.society_agent_chats(root_chat)
158
+ end
159
+ end
@@ -21,7 +21,7 @@ What is my name?
21
21
  # mock backend records what the agent actually sent.
22
22
  LLM::Mock.script('Your name is Miguel')
23
23
 
24
- res = agent.prompt chat, persist: false, endpoint: 'mock'
24
+ res = agent.prompt chat, persist: false, endpoint: 'mock', backend: :mock
25
25
 
26
26
  assert_equal 'Your name is Miguel', res
27
27
 
@@ -42,7 +42,109 @@ class TestLLMEmbed < Test::Unit::TestCase
42
42
  assert cos(shared, similar) > cos(shared, other)
43
43
  end
44
44
 
45
+ # ScoutCoder: hermetic against request-level env. EMBED_ENDPOINT /
46
+ # LLM_ENDPOINT act as an EXPLICIT endpoint request (same precedence as the
47
+ # options hash), so a value leaked into the test process would make even a
48
+ # backend-pinned call raise "Endpoint not found". Neutralize both for the
49
+ # duration of the assertion; the repo-level config pin (backend: :mock)
50
+ # then governs dispatch. The raise-on-requested-but-absent behavior itself
51
+ # is covered in test_embed_missing_endpoint_raises.
45
52
  def test_embed_explicit_backend
46
- assert_equal LLM::Mock.embed('a text', endpoint: :mock), LLM.embed('a text', backend: :mock)
53
+ saved_embed_endpoint, saved_llm_endpoint = ENV['EMBED_ENDPOINT'], ENV['LLM_ENDPOINT']
54
+ ENV.delete 'EMBED_ENDPOINT'
55
+ ENV.delete 'LLM_ENDPOINT'
56
+ begin
57
+ assert_equal LLM::Mock.embed('a text', endpoint: :mock), LLM.embed('a text', backend: :mock)
58
+ ensure
59
+ ENV['EMBED_ENDPOINT'] = saved_embed_endpoint if saved_embed_endpoint
60
+ ENV['LLM_ENDPOINT'] = saved_llm_endpoint if saved_llm_endpoint
61
+ end
62
+ end
63
+
64
+ # ScoutCoder: bug M4 regression. The endpoint yaml lookup used the
65
+ # extensionless `Scout.etc.AI[endpoint].exists?`, so a standard
66
+ # `etc/AI/<endpoint>.yaml` was never merged (asymmetric with ask/image,
67
+ # which use find_with_extension(:yaml)), and a missing endpoint fell
68
+ # through to the config defaults silently. Both probed offline here with
69
+ # a throwaway endpoint yaml and a recording backend in the registry.
70
+ def test_embed_endpoint_yaml_is_merged
71
+ base = tmpdir
72
+ etc_ai = Path.setup(base)['etc/AI']
73
+ Open.mkdir(etc_ai)
74
+ Open.write(etc_ai['m4_endpoint.yaml'], {'backend' => 'm4_rec', 'model' => 'm4-model'}.to_yaml)
75
+
76
+ Scout.prepend_path :m4_test_etc, File.join(base, '{TOPLEVEL}/{SUBPATH}')
77
+ received = nil
78
+ LLM::BACKENDS[:m4_rec] = Module.new do
79
+ define_singleton_method(:embed) do |_text, options|
80
+ $m4_received = IndiferentHash.setup(options.dup)
81
+ [0.0] * LLM::Mock::DIMENSIONS
82
+ end
83
+ end
84
+
85
+ # sanity: the yaml exists for the with-extension lookup and NOT for the
86
+ # extensionless one that used to gate the merge
87
+ assert Scout.etc.AI[:m4_endpoint].find_with_extension(:yaml).exists?
88
+ assert !Scout.etc.AI[:m4_endpoint].exists?
89
+
90
+ LLM.embed('a text', endpoint: :m4_endpoint)
91
+ assert_equal 'm4-model', $m4_received['model']
92
+
93
+ # an endpoint yaml naming a backend drives dispatch through the registry
94
+ LLM::BACKENDS.delete(:m4_rec)
95
+ Open.write(etc_ai['m4_endpoint.yaml'], {'backend' => 'mock'}.to_yaml)
96
+ assert_equal LLM::Mock::DIMENSIONS, LLM.embed('a text', endpoint: :m4_endpoint).length
97
+ ensure
98
+ LLM::BACKENDS.delete(:m4_rec)
99
+ Scout.path_maps.delete(:m4_test_etc) if Scout.path_maps.include?(:m4_test_etc)
100
+ Scout.map_order.delete(:m4_test_etc) if Scout.map_order.include?(:m4_test_etc)
101
+ $m4_received = nil
102
+ end
103
+
104
+ def test_embed_missing_endpoint_raises
105
+ # ask/image raise "Endpoint not found <name>" for a requested-but-absent
106
+ # endpoint; embed used to fall through to the config defaults silently.
107
+ # The synthesized `:embed` fallback name is NOT a request, so a call
108
+ # without any endpoint still works (backend-configured path).
109
+ error = assert_raise(RuntimeError) { LLM.embed('a text', endpoint: :m4_no_such_endpoint) }
110
+ assert_include error.message, 'Endpoint not found'
111
+
112
+ # ScoutCoder: hermetic. With no explicit endpoint the synthesized `:embed`
113
+ # name is still resolved as etc/AI/embed.yaml, and a user-level file there
114
+ # (~/.scout/etc/AI/embed.yaml, e.g. `backend: ollama`) legitimately
115
+ # contributes defaults AHEAD of the config-pinned backend, exactly like
116
+ # LLM.ask for its endpoint yaml. On an account with such a file (and
117
+ # OLLAMA_URL/OLLAMA_KEY exported) the bare call dispatches to that backend
118
+ # and returns its dimensionality (observed: 1024 for mxbai-embed-large),
119
+ # so this no-endpoint assertion pins the backend explicitly instead of
120
+ # relying on the absence of user configuration. The endpoint resolution
121
+ # path is still exercised: the synthesized `:embed` name is looked up as a
122
+ # yaml and must not raise, while a genuinely requested endpoint does.
123
+ #
124
+ # EMBED_ENDPOINT/LLM_ENDPOINT are REQUEST-level environment, i.e. an
125
+ # explicit endpoint request for every embed call; a leaked value would
126
+ # make even these calls raise "Endpoint not found". Neutralize it inside
127
+ # the test (ENV.delete inside an ensure-protected block) so the
128
+ # environment-dependent assertions below are hermetic while the repo-level
129
+ # config pin (backend: :mock in test_helper) still governs resolution.
130
+ saved_embed_endpoint, saved_llm_endpoint = ENV['EMBED_ENDPOINT'], ENV['LLM_ENDPOINT']
131
+ ENV.delete 'EMBED_ENDPOINT'
132
+ ENV.delete 'LLM_ENDPOINT'
133
+ begin
134
+ assert_equal LLM::Mock::DIMENSIONS, LLM.embed('a text', backend: :mock).length
135
+ # The bare call exercises the synthesized-fallback path itself: no raise,
136
+ # and it uses the offline backend UNLESS the environment legitimately
137
+ # configures an etc/AI/embed.yaml (a user-level file resolves through the
138
+ # same path maps ask/image use). Keep the assertion hermetic: assert the
139
+ # offline dimensionality only when no such endpoint yaml is resolvable,
140
+ # otherwise the dimensionality belongs to the configured backend and the
141
+ # pinned call above already proves the fallback does not raise.
142
+ unless Scout.etc.AI[:embed].find_with_extension(:yaml).exists?
143
+ assert_equal LLM::Mock::DIMENSIONS, LLM.embed('a text').length
144
+ end
145
+ ensure
146
+ ENV['EMBED_ENDPOINT'] = saved_embed_endpoint if saved_embed_endpoint
147
+ ENV['LLM_ENDPOINT'] = saved_llm_endpoint if saved_llm_endpoint
148
+ end
47
149
  end
48
150
  end
@@ -0,0 +1,299 @@
1
+ require File.expand_path(__FILE__).sub(%r(/test/.*), '/test/test_helper.rb')
2
+ require File.expand_path(__FILE__).sub(%r(.*/test/), '').sub(/test_(.*)\.rb/,'\\1')
3
+ require 'scout/llm/request_context'
4
+ require 'scout/llm/tools/call'
5
+ require 'scout/llm/tools/workflow'
6
+ require 'scout/llm/ask'
7
+ require 'open3'
8
+
9
+ class TestLLMRequestContext < Test::Unit::TestCase
10
+ def context_workflow
11
+ @context_workflow ||= Module.new do
12
+ extend Workflow
13
+ self.name = 'RequestContextTestWorkflow'
14
+ input :value, :string
15
+ task :echo => :string do |value|
16
+ value
17
+ end
18
+ task :read_context => :string do
19
+ request_context.to_json
20
+ end
21
+ dep :read_context
22
+ task :parent => :string do
23
+ step(:read_context).load
24
+ end
25
+ end
26
+ end
27
+
28
+ def test_projection_is_serializable_and_excludes_unsafe_fields
29
+ agent = Object.new
30
+ context = LLM::RequestContext.project(
31
+ endpoint: 'local', backend: :openai, model: 'gpt-test',
32
+ agent: agent, client: agent, tools: [proc {}],
33
+ messages: [{role: 'user'}], previous_response_id: 'secret',
34
+ nested: {keep: true, api_key: 'secret', 'X-Api-Key' => 'secret', finite: 1.5,
35
+ nan: Float::NAN, infinity: Float::INFINITY},
36
+ invalid_encoding: "bad\xFF".force_encoding(Encoding::UTF_8)
37
+ )
38
+
39
+ assert_equal 'local', context[:endpoint]
40
+ assert_equal 'openai', context[:backend]
41
+ assert_equal 'gpt-test', context[:model]
42
+ assert_equal({keep: true, finite: 1.5}, context[:nested])
43
+ assert(!context.key?(:agent))
44
+ assert(!context.key?(:client))
45
+ assert(!context.key?(:tools))
46
+ assert(!context.key?(:messages))
47
+ assert(!context.key?(:previous_response_id))
48
+ assert(JSON.parse(JSON.generate(context)))
49
+ assert_equal 1.5, context[:nested][:finite]
50
+ assert(!context[:nested].key?(:nan))
51
+ assert(!context[:nested].key?(:infinity))
52
+ assert_equal "bad\uFFFD", context[:invalid_encoding]
53
+ end
54
+
55
+ def test_projection_handles_malformed_hash_keys
56
+ malformed = "bad\xFFkey".force_encoding(Encoding::UTF_8)
57
+ context = LLM::RequestContext.project(malformed => 'value')
58
+
59
+ assert_equal 'value', context["bad\uFFFDkey".to_sym]
60
+ assert JSON.parse(JSON.generate(context))
61
+ end
62
+
63
+ def test_tool_callback_preserves_two_argument_lambda_and_supports_three
64
+ call = {'id' => 'call-1', 'name' => 'echo', 'arguments' => {value: 'x'}}
65
+ two_seen = nil
66
+ LLM.tool_response(call, request_context: {request_id: 'R'}) do |name, arguments|
67
+ two_seen = [name, arguments]
68
+ 'ok'
69
+ end
70
+ assert_equal ['echo', {value: 'x'}], two_seen
71
+
72
+ three_seen = nil
73
+ LLM.tool_response(call, request_context: {request_id: 'R'}) do |name, arguments, context|
74
+ three_seen = [name, arguments, context]
75
+ 'ok'
76
+ end
77
+ assert_equal ['echo', {value: 'x'}, {request_id: 'R'}], three_seen
78
+
79
+ strict_seen = nil
80
+ strict = ->(name, arguments) { strict_seen = [name, arguments]; 'ok' }
81
+ LLM.tool_response(call, request_context: {request_id: 'R'}, &strict)
82
+ assert_equal ['echo', {value: 'x'}], strict_seen
83
+ end
84
+
85
+ def test_strict_two_argument_tool_response_lambda
86
+ call = {'id' => 'call-strict', 'name' => 'echo', 'arguments' => {value: 'x'}}
87
+ strict = ->(name, arguments) { [name, arguments] }
88
+ response = LLM.tool_response(call, request_context: {request_id: 'R'}, &strict)
89
+ assert_equal ['echo', {value: 'x'}].to_json, response[:content]
90
+ end
91
+
92
+ def test_process_calls_forwards_context_without_workflow_parameters
93
+ value = 'not-context'
94
+ context = {request_id: 'R1', endpoint: 'local', backend: 'openai', model: 'gpt-test'}
95
+ definition = LLM.task_tool_definition(context_workflow, :echo)
96
+ tools = {'echo' => [context_workflow, definition]}
97
+ calls = [{'id' => 'call-1', 'name' => 'echo', 'arguments' => {value: value}}]
98
+
99
+ result = LLM.process_calls(tools, calls, request_context: context)
100
+ assert_equal value, JSON.parse(result[1][:content])['content']
101
+
102
+ job = context_workflow.job(:echo, nil, value: value)
103
+ assert_equal value, job.run
104
+ assert_equal JSON.parse(JSON.generate(version: 1, fields: context)), job.info[:request_context]
105
+ assert_equal value, job.info[:provided_inputs]['value']
106
+ assert(!job.info[:provided_inputs].key?('request_context'))
107
+ end
108
+
109
+ def test_task_body_reads_context_from_persisted_info_without_identity_change
110
+ context = {request_id: 'body-R', endpoint: 'test', backend: 'mock'}
111
+ first = context_workflow.job(:read_context, nil, value: 'body-context')
112
+ first.extend(LLM::RequestContext::StepExtension)
113
+ first.register_request_context(context)
114
+ first.clean
115
+ first.produce
116
+ loaded = Step.load(first.path)
117
+ expected_path = first.path.to_s
118
+ assert_equal expected_path, loaded.path.to_s
119
+ assert_equal first.inputs, context_workflow.job(:read_context, nil, value: 'body-context').inputs
120
+ assert_equal expected_path, context_workflow.job(:read_context, nil, value: 'body-context').path.to_s
121
+ assert_equal JSON.parse(JSON.generate(version: 1, fields: context)), loaded.info[:request_context]
122
+ assert(!loaded.info[:provided_inputs].keys.any? { |key| key.to_s == 'request_context' })
123
+ assert_equal context.transform_keys(&:to_s), JSON.parse(loaded.load)
124
+ end
125
+
126
+ def test_llm_ask_forwards_request_context_to_workflow_tool_step
127
+ context = {request_id: 'ask-R', endpoint: 'mock', backend: 'mock'}
128
+ tools = {'echo' => [context_workflow, LLM.task_tool_definition(context_workflow, :echo)]}
129
+ backend = Module.new
130
+ backend.define_singleton_method(:ask) do |_messages, options|
131
+ LLM.process_calls(options[:tools],
132
+ [{name: 'echo', arguments: {value: 'ask-context'}, id: 'ask-call'}],
133
+ request_context: options[:request_context])
134
+ 'done'
135
+ end
136
+ LLM.register_backend(:request_context_test, backend)
137
+
138
+ result = LLM.ask('Return the result from the echo tool.', tools: tools,
139
+ request_context: context, persist: false, backend: :request_context_test)
140
+
141
+ assert_include result, 'done'
142
+ step = context_workflow.job(:echo, nil, value: 'ask-context')
143
+ assert_equal JSON.parse(JSON.generate(version: 1, fields: context)), step.info[:request_context]
144
+ assert_equal 'ask-context', step.info[:provided_inputs]['value']
145
+ assert(!step.info[:provided_inputs].key?('request_context'))
146
+ end
147
+
148
+ def test_save_file_keyword_remains_compatible
149
+ calls = [{'id' => 'call-1', 'name' => 'echo', 'arguments' => {value: 'saved'}}]
150
+ tools = {'echo' => [context_workflow, LLM.task_tool_definition(context_workflow, :echo)]}
151
+ TmpFile.with_dir do |dir|
152
+ save_file = File.join(dir, 'chat')
153
+ result = LLM.process_calls(tools, calls, save_file: save_file,
154
+ request_context: {request_id: 'R2'})
155
+ assert_equal 'saved', JSON.parse(result[1][:content])['content']
156
+ end
157
+ end
158
+ def test_done_and_contextualized_dependencies_are_not_overwritten
159
+ context = {request_id: 'existing-R', endpoint: 'test'}
160
+ dependency = context_workflow.job(:read_context)
161
+ dependency.extend(LLM::RequestContext::StepExtension)
162
+ dependency.register_request_context(context)
163
+ dependency.clean
164
+ dependency.produce
165
+ before = File.binread(dependency.info_file)
166
+
167
+ parent = LLM.call_workflow(context_workflow, :parent, {},
168
+ request_context: {request_id: 'parent-R'})
169
+ parent.clean
170
+ parent.produce
171
+
172
+ assert_equal before, File.binread(dependency.info_file)
173
+ assert_equal context.transform_keys(&:to_s), JSON.parse(Step.load(dependency.path).load)
174
+ end
175
+
176
+ def test_dependency_task_body_reads_parent_context
177
+ context = {request_id: 'dependency-R', endpoint: 'test'}
178
+ parent = LLM.call_workflow(context_workflow, :parent, {}, request_context: context)
179
+ dependency_path = context_workflow.job(:read_context).path
180
+ parent.clean
181
+ assert(!File.exist?(dependency_path.to_s + '.info'))
182
+ parent.produce
183
+
184
+ dependency = Step.load(dependency_path)
185
+ assert_equal context.transform_keys(&:to_s), JSON.parse(dependency.load)
186
+ assert_equal JSON.parse(JSON.generate(version: 1, fields: context)), dependency.info[:request_context]
187
+ assert(!dependency.info[:provided_inputs].keys.any? { |key| key.to_s == 'request_context' })
188
+ end
189
+
190
+ def test_context_does_not_change_workflow_job_identity
191
+ inputs = {value: 'same'}
192
+ first = LLM.call_workflow(context_workflow, :echo, inputs,
193
+ request_context: {request_id: 'one'})
194
+ second = LLM.call_workflow(context_workflow, :echo, inputs,
195
+ request_context: {request_id: 'two'})
196
+ assert_equal first.path.to_s, second.path.to_s
197
+ end
198
+
199
+ def test_replay_in_a_cold_process_does_not_replace_producer_context
200
+ value = 'cold-replay'
201
+ definition = LLM.task_tool_definition(context_workflow, :echo)
202
+ tools = {'echo' => [context_workflow, definition]}
203
+ calls = [{'id' => 'call-1', 'name' => 'echo', 'arguments' => {value: value}}]
204
+
205
+ LLM.process_calls(tools, calls, request_context: {request_id: 'A'})
206
+ job = context_workflow.job(:echo, nil, value: value)
207
+ assert_equal 'A', job.info[:request_context][:fields][:request_id]
208
+ original_info = File.binread(job.info_file)
209
+
210
+ script = File.join(tmpdir.to_s, 'cold_replay.rb')
211
+ File.write(script, <<~RUBY)
212
+ $LOAD_PATH.unshift #{File.expand_path('lib').inspect}
213
+ require 'scout'
214
+ require 'scout/llm/tools/call'
215
+ require 'scout/llm/tools/workflow'
216
+ module RequestContextTestWorkflow
217
+ extend Workflow
218
+ input :value, :string
219
+ task :echo => :string do |value|
220
+ value
221
+ end
222
+ end
223
+ Workflow.directory = Path.setup(#{Workflow.directory.to_s.inspect})
224
+ wf = RequestContextTestWorkflow
225
+ definition = LLM.task_tool_definition(wf, :echo)
226
+ LLM.process_calls({'echo' => [wf, definition]},
227
+ [{'id' => 'cold', 'name' => 'echo', 'arguments' => {value: #{value.inspect}}}],
228
+ request_context: {request_id: 'B'})
229
+ RUBY
230
+ stdout, stderr, status = Open3.capture3(RbConfig.ruby, script)
231
+ assert status.success?, "cold replay failed: #{stdout}\n#{stderr}"
232
+ assert_equal original_info, File.binread(job.info_file)
233
+ assert_equal 'A', Step.load(job.path).info[:request_context][:fields][:request_id]
234
+ end
235
+
236
+ def test_concurrent_producers_write_one_first_context_and_one_raw_key
237
+ value = 'concurrent-producer'
238
+ definition = LLM.task_tool_definition(context_workflow, :echo)
239
+ tools = {'echo' => [context_workflow, definition]}
240
+ calls = [
241
+ {'id' => 'call-1', 'name' => 'echo', 'arguments' => {value: value}},
242
+ {'id' => 'call-2', 'name' => 'echo', 'arguments' => {value: value}},
243
+ {'id' => 'call-3', 'name' => 'echo', 'arguments' => {value: value}},
244
+ {'id' => 'call-4', 'name' => 'echo', 'arguments' => {value: value}},
245
+ {'id' => 'call-5', 'name' => 'echo', 'arguments' => {value: value}}
246
+ ]
247
+ errors = Queue.new
248
+
249
+ threads = (0...4).map do |i|
250
+ Thread.new do
251
+ begin
252
+ sleep rand
253
+ LLM.process_calls(tools, [calls[i]], request_context: {request_id: "producer-#{i}"})
254
+ rescue Exception => e
255
+ errors << e
256
+ end
257
+ end
258
+ end
259
+ threads.each(&:join)
260
+ assert errors.empty?, errors.size.times.map { errors.pop.message }.join("\n")
261
+
262
+ job = context_workflow.job(:echo, nil, value: value)
263
+ raw_text = File.binread(job.info_file)
264
+ raw = JSON.parse(raw_text)
265
+ request_context_keys = raw.keys.select { |key| key == 'request_context' }
266
+ assert_equal ['request_context'], request_context_keys
267
+ assert_kind_of Hash, raw['request_context']
268
+ assert_equal 1, raw['request_context']['version']
269
+ assert_match(/producer-\d+/, raw['request_context']['fields']['request_id'])
270
+ assert_equal 1, raw_text.scan(/"request_context"\s*:/).length
271
+ assert_equal 1, raw.keys.count { |key| key == 'request_context' }
272
+ end
273
+
274
+ def test_request_context_exec
275
+ context = {request_id: 'body-R', endpoint: 'test', backend: 'mock'}
276
+
277
+ job = self.context_workflow.job(:read_context)
278
+ job.extend(LLM::RequestContext::StepExtension)
279
+ job.register_request_context(context)
280
+ assert_equal context.to_json, job.run
281
+ assert job.info_file.exists?
282
+ refute Open.exist?(job.info_file + '.request_context')
283
+ refute Open.exist?(job.info_file + '.request_context.lock')
284
+
285
+
286
+ job = self.context_workflow.job(:read_context, 'exec')
287
+ job.extend(LLM::RequestContext::StepExtension)
288
+ assert_equal 'null', job.exec
289
+ refute job.info_file.exists?
290
+ refute Open.exist?(job.info_file + '.request_context')
291
+ refute Open.exist?(job.info_file + '.request_context.lock')
292
+
293
+ job.register_request_context(context)
294
+ assert_equal context.to_json, job.exec
295
+ refute job.info_file.exists?
296
+ refute Open.exist?(job.info_file + '.request_context')
297
+ refute Open.exist?(job.info_file + '.request_context.lock')
298
+ end
299
+ end