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
@@ -3,8 +3,8 @@ require File.expand_path(__FILE__).sub(%r(.*/test/), '').sub(/test_(.*)\.rb/,'\1
3
3
 
4
4
  class TestTorch < Test::Unit::TestCase
5
5
  def test_linear
6
- omit "No python environment" unless Availability.python?
7
- omit "Torch not installed" unless Availability.python_modules?(:torch)
6
+ omit "No python environment" unless Availability.python?(route: :embedded)
7
+ omit "Torch not installed" unless Availability.python_modules?(:torch, route: :embedded)
8
8
  model = nil
9
9
 
10
10
  TmpFile.with_dir do |dir|
@@ -71,3 +71,55 @@ class TestTorch < Test::Unit::TestCase
71
71
  end
72
72
  end
73
73
 
74
+
75
+ class TestTorchDefaults < Test::Unit::TestCase
76
+ # Regression test for the @criterion default-wiring bug: the train loop
77
+ # used to assign an SGD optimizer to @criterion (TorchModel.optimizer
78
+ # instead of TorchModel.criterion), so default training failed with
79
+ # "TypeError: Non-callable Python object was given" (doc/Model.md
80
+ # documents MSELoss as the default criterion).
81
+ def test_default_criterion_is_mseloss_and_train_works
82
+ omit "No python environment" unless Availability.python?(route: :embedded)
83
+ omit "Torch not installed" unless Availability.python_modules?(:torch, route: :embedded)
84
+
85
+ model = nil
86
+
87
+ TmpFile.with_dir do |dir|
88
+
89
+ TorchModel.init_python
90
+
91
+ model = TorchModel.new dir
92
+ model.state = ScoutPython.torch.nn.Linear.new(1, 1)
93
+ # NOTE: neither criterion nor optimizer is set on purpose; this
94
+ # exercises the default wiring path.
95
+
96
+ model.extract_features do |f|
97
+ [f]
98
+ end
99
+
100
+ model.post_process do |v,list|
101
+ list ? list.collect{|vv| vv.first } : v.first
102
+ end
103
+
104
+ model.add 5.0, [10.0]
105
+ model.add 10.0, [20.0]
106
+
107
+ model.options[:training_args][:epochs] = 1000
108
+
109
+ model.train
110
+
111
+ # The default criterion is the documented MSELoss, not an optimizer
112
+ assert PyCall.getattr(model.criterion, :__class__).to_s.include?('MSELoss')
113
+
114
+ w = TorchModel.get_weights(model.state).to_ruby.first.first
115
+
116
+ assert w > 1.8
117
+ assert w < 2.2
118
+
119
+ y = model.eval(100.0)
120
+
121
+ assert y > 150.0
122
+ assert y < 250.0
123
+ end
124
+ end
125
+ end
@@ -1,231 +1,129 @@
1
- # Test support: bounded availability probes for conditional test omissions.
1
+ # Test support: runtime and domain-specific availability probes.
2
2
  #
3
3
  # Not named test_*.rb on purpose: the Rakefile test pattern
4
4
  # ('test/**/test_*.rb') must not collect this file.
5
5
  #
6
- # Every probe returns true/false (never raises, never downloads, never hangs).
7
- # Intended usage in a test:
8
- #
9
- # omit 'torch CUDA unavailable' unless Availability.cuda?
10
- #
11
- # Guidelines honoured here:
12
- # * Huggingface model presence is checked against the local HF cache only
13
- # (HF_HOME/hub or ~/.cache/huggingface/hub), NEVER through the
14
- # transformers API: importing transformers or building a tokenizer would
15
- # start a multi-GB download for anything that is not already cached.
16
- # * Python module probes run `python -c "import ..."` in a fresh process
17
- # with a hard timeout, so a hanging import cannot block the suite.
18
- # * Results are memoized per process: probes are cheap but not free.
19
- module Availability
20
- DEFAULT_TIMEOUT = 60
6
+ # Python and R runtime probes are opt-in Scout-Rig test helpers. CUDA and
7
+ # Hugging Face cache checks remain Scout-AI-specific; endpoint configuration
8
+ # remains local and endpoint reachability is a TCP-only check. None of these
9
+ # checks performs HTTP/inference or downloads a model.
10
+ require 'scout-rig/testing/availability'
11
+ require 'uri'
21
12
 
13
+ module Availability
22
14
  class << self
23
- def memo(name)
24
- cache = (@cache ||= {})
25
- return cache[name] if cache.key?(name)
26
- cache[name] = begin
27
- yield
28
- rescue Exception
29
- false
30
- end
31
- end
32
-
33
- def python_executable
34
- ENV['SCOUT_TEST_PYTHON'] || 'python'
35
- end
36
-
37
- # python itself is usable (python executable present and runnable)
38
- def python?
39
- memo(:python) do
40
- run_bounded([python_executable, '-c', 'import sys; sys.exit(0)'], 30)
41
- true
42
- end
15
+ def python?(route: ScoutRig::Testing::Availability::DEFAULT_ROUTE)
16
+ ScoutRig::Testing::Availability.python?(route: route)
43
17
  end
44
18
 
45
- # all listed python modules import cleanly (fresh process, bounded)
46
- def python_modules?(*mods)
47
- memo(:"python_modules_#{mods.join(',')}") do
48
- raise Errno::ENOENT unless python?
49
- code = mods.collect { |m| "import #{m}" } * ';'
50
- _out, _err, status = run_bounded([python_executable, '-c', code], DEFAULT_TIMEOUT, capture: true)
51
- status == 0
52
- end
19
+ def python_modules?(*modules, route: ScoutRig::Testing::Availability::DEFAULT_ROUTE)
20
+ ScoutRig::Testing::Availability.python_modules?(*modules, route: route)
53
21
  end
54
22
 
55
- # informative reason string when a python module is missing, nil otherwise
56
- def python_modules_reason(*mods)
57
- return 'python unavailable' unless python?
58
- code = mods.collect { |m| "import #{m}" } * ';'
59
- out, _err, status = run_bounded([python_executable, '-c', code], DEFAULT_TIMEOUT, capture: true)
60
- return nil if status == 0
61
- "python modules missing (#{mods * ','}): #{out.split("\n").last.to_s.strip}"
23
+ def python_modules_reason(*modules, route: ScoutRig::Testing::Availability::DEFAULT_ROUTE)
24
+ ScoutRig::Testing::Availability.python_modules_reason(*modules, route: route)
62
25
  end
63
26
 
64
27
  # torch is importable (does NOT imply CUDA)
65
- def torch?
66
- python_modules?('torch')
28
+ def torch?(route: :embedded)
29
+ python_modules?(:torch, route: route)
67
30
  end
68
31
 
69
- # torch is importable AND reports a usable CUDA device
32
+ # torch is importable AND reports a usable CUDA device. The subprocess
33
+ # uses Scout-Rig's embedded-interpreter selection and Scout-Essentials'
34
+ # bounded argv executor; this is only an omission probe, never a rescue
35
+ # around the model's real PyCall operations.
70
36
  def cuda?
71
- memo(:cuda) do
72
- return false unless torch?
73
- code = 'import sys, torch; sys.exit(0 if torch.cuda.is_available() else 1)'
74
- _out, _err, status = run_bounded([python_executable, '-c', code], DEFAULT_TIMEOUT, capture: true)
75
- status == 0
76
- end
37
+ return false unless torch?(route: :embedded)
38
+
39
+ executable = ScoutRig::Testing::Availability.embedded_python
40
+ return false unless executable
41
+
42
+ result = Scout::Testing::Availability.run_command(
43
+ [executable, '-c', 'import sys, torch; sys.exit(0 if torch.cuda.is_available() else 1)'],
44
+ timeout: 30
45
+ )
46
+ result.success? && result.exit_status == 0
77
47
  end
78
48
 
79
- # A Huggingface model is already in the local cache; this NEVER triggers a
80
- # download (see the note at the top of the file).
49
+ # A Hugging Face model is already in the local cache; this NEVER triggers
50
+ # a download. HF_HUB_CACHE overrides HF_HOME/hub, matching the cache
51
+ # layout used by huggingface_hub.
81
52
  def hf_model_cached?(repo)
82
- memo(:"hf_model_#{repo}") do
83
- hub = ENV['HF_HOME'] ? File.join(ENV['HF_HOME'], 'hub') : File.join(Dir.home, '.cache', 'huggingface', 'hub')
84
- repo_dir = 'models--' + repo.to_s.tr('/', '--')
85
- path = File.join(hub, repo_dir)
86
- Dir.exist?(path) && Dir.glob(File.join(path, 'snapshots', '*')).any?
87
- end
53
+ hub = ENV['HF_HUB_CACHE']
54
+ hub ||= File.join(ENV['HF_HOME'] || File.join(Dir.home, '.cache', 'huggingface'), 'hub')
55
+ repo_dir = 'models--' + repo.to_s.gsub('/', '--')
56
+ path = File.join(hub, repo_dir)
57
+ Dir.exist?(path) && Dir.glob(File.join(path, 'snapshots', '*')).any?
88
58
  end
89
59
 
90
- # Reason for a missing huggingface model
91
60
  def hf_model_reason(repo)
92
- return "huggingface model #{repo} not in local cache (HF_HOME=#{ENV['HF_HOME'] || '~/.cache/huggingface'}); probing would download it" unless hf_model_cached?(repo)
93
- nil
61
+ return nil if hf_model_cached?(repo)
62
+
63
+ cache = ENV['HF_HUB_CACHE'] || ENV['HF_HOME'] || '~/.cache/huggingface'
64
+ "huggingface model #{repo} not in local cache (cache root=#{cache}); probing would download it"
94
65
  end
95
66
 
96
- # Rscript is present
67
+ # Scout-Rig offers reference Rscript/package probes; these do not imply
68
+ # an R runtime in Scout-AI. Keep these adapters because the integration
69
+ # model tests use them to omit when e1071 is unavailable.
97
70
  def rscript?
98
- memo(:rscript) { which?('Rscript') }
71
+ ScoutRig::Testing::Availability.rscript?
99
72
  end
100
73
 
101
- # R is present and the listed packages are installed (bounded Rscript -e)
102
- def r_packages?(*pkgs)
103
- memo(:"r_packages_#{pkgs.join(',')}") do
104
- return false unless rscript?
105
- code = "cat(if (all(c(#{pkgs.collect { |p| "'#{p}'" } * ', '}) %in% rownames(installed.packages()))) 'yes' else 'no')"
106
- out, _err, status = run_bounded(['Rscript', '-e', code], DEFAULT_TIMEOUT, capture: true)
107
- status == 0 && out.strip == 'yes'
108
- end
74
+ def r_packages?(*packages)
75
+ ScoutRig::Testing::Availability.r_packages?(*packages)
109
76
  end
110
77
 
111
- def r_packages_reason(*pkgs)
112
- return 'Rscript not found' unless rscript?
113
- return nil if r_packages?(*pkgs)
114
- "R packages missing: #{pkgs * ','}"
78
+ def r_packages_reason(*packages)
79
+ ScoutRig::Testing::Availability.r_packages_reason(*packages)
115
80
  end
116
81
 
117
- #{{{ endpoints
118
-
119
- # An endpoint yaml exists in the Scout configuration paths (test/etc/AI,
120
- # ~/.scout/etc/AI, ...). Purely local: no network access.
82
+ # An endpoint yaml exists in Scout's configuration paths. This is a
83
+ # local filesystem check; it never contacts the endpoint.
121
84
  def endpoint_configured?(endpoint)
122
- memo(:"endpoint_configured_#{endpoint}") do
123
- Scout.etc.AI[endpoint.to_s].find_with_extension(:yaml).exists?
124
- end
85
+ Scout.etc.AI[endpoint.to_s].find_with_extension(:yaml).exists?
125
86
  end
126
87
 
127
- # The endpoint points to a host:port that accepts a TCP connection within
128
- # the timeout. Only probed for endpoints whose config carries a url;
129
- # endpoints without a url (mock, relay through scp, ...) count as
88
+ # The endpoint's URL accepts a TCP connection within timeout. This only
89
+ # establishes TCP reachability, not HTTP, authentication or inference.
90
+ # Endpoints without URLs (mock, relay through scp, ...) count as
130
91
  # reachable once configured.
131
92
  def endpoint_reachable?(endpoint, timeout = 5)
132
- memo(:"endpoint_reachable_#{endpoint}") do
133
- path = Scout.etc.AI[endpoint.to_s].find_with_extension(:yaml)
134
- return false unless path.exists?
135
- url = path.yaml[:url] || path.yaml['url']
136
- return true if url.nil?
137
-
138
- require 'uri'
139
- require 'socket'
140
- uri = URI.parse(url.to_s)
141
- port = uri.port || (uri.scheme == 'https' ? 443 : 80)
142
- begin
143
- Timeout.timeout(timeout) do
144
- TCPSocket.open(uri.host, port) { |s| s.close }
145
- end
146
- true
147
- rescue Exception
148
- false
149
- end
150
- end
93
+ path = Scout.etc.AI[endpoint.to_s].find_with_extension(:yaml)
94
+ return false unless path.exists?
95
+
96
+ url = path.yaml[:url] || path.yaml['url']
97
+ return true if url.nil?
98
+
99
+ uri = URI.parse(url.to_s)
100
+ port = uri.port || (uri.scheme == 'https' ? 443 : 80)
101
+ Scout::Testing::Availability.tcp_reachable?(uri.host, port, timeout: timeout)
102
+ rescue URI::InvalidURIError
103
+ false
151
104
  end
152
105
 
153
106
  # Combined: configured AND (no url OR reachable)
154
107
  def endpoint_available?(endpoint)
155
- return false unless endpoint_configured?(endpoint)
156
- endpoint_reachable?(endpoint)
108
+ endpoint_configured?(endpoint) && endpoint_reachable?(endpoint)
157
109
  end
158
110
 
159
111
  def endpoint_reason(endpoint)
160
112
  return "endpoint #{endpoint} not configured (no yaml in the Scout AI paths)" unless endpoint_configured?(endpoint)
161
113
  return "endpoint #{endpoint} configured but not reachable" unless endpoint_reachable?(endpoint)
114
+
162
115
  nil
163
116
  end
164
117
 
165
- # All endpoint names defined in Scout.etc.AI across the search paths
166
- # (test/etc/AI plus the user configuration). Local filesystem only.
118
+ # All endpoint names defined in Scout.etc.AI across the search paths.
167
119
  def configured_endpoints
168
- memo(:configured_endpoints) do
169
- Scout.etc.AI.glob('*.yaml').collect { |f| File.basename(f, '.yaml') }.uniq
170
- end
120
+ Scout.etc.AI.glob('*.yaml').collect { |file| File.basename(file, '.yaml') }.uniq
171
121
  end
172
122
 
173
123
  # Endpoints that are real inference services (anything but the offline
174
124
  # mock one defined by this test suite).
175
125
  def real_endpoints
176
- memo(:real_endpoints) do
177
- configured_endpoints.reject { |e| e == 'mock' }
178
- end
179
- end
180
-
181
- #{{{ internals
182
-
183
- def which?(cmd)
184
- ENV['PATH'].to_s.split(File::PATH_SEPARATOR).any? do |dir|
185
- path = File.join(dir, cmd.to_s)
186
- File.executable?(path)
187
- end
188
- end
189
-
190
- # Runs cmd with a hard timeout. Returns [stdout, stderr, exit_status].
191
- # ScoutCoder: Open3.capture3 threads cannot be killed, so Timeout.timeout
192
- # only breaks the wait; the child is detached with Process.kill(:KILL) to
193
- # guarantee the probe returns even when the command hangs (e.g. a python
194
- # import that blocks on a broken environment).
195
- def run_bounded(cmd, timeout = DEFAULT_TIMEOUT, capture: true)
196
- out_r, out_w = IO.pipe
197
- err_r, err_w = IO.pipe
198
-
199
- pid = Process.spawn(*cmd, out: out_w, err: err_w)
200
- out_w.close
201
- err_w.close
202
-
203
- status = nil
204
- begin
205
- Timeout.timeout(timeout) do
206
- out = capture ? out_r.read : nil
207
- err = capture ? err_r.read : nil
208
- _pid, status = Process.wait2(pid)
209
- return [out.to_s, err.to_s, status.exitstatus]
210
- end
211
- rescue Timeout::Error
212
- begin
213
- Process.kill(:KILL, pid)
214
- rescue Errno::ESRCH
215
- end
216
- Process.detach(pid)
217
- return ['', 'timeout', -1]
218
- rescue Errno::ENOENT
219
- begin
220
- Process.kill(:KILL, pid)
221
- rescue Errno::ESRCH, Errno::EPERM
222
- end
223
- return ['', 'not found', -1]
224
- ensure
225
- out_r.close rescue nil
226
- err_r.close rescue nil
227
- end
228
- ['', 'unknown', -1]
126
+ configured_endpoints.reject { |endpoint| endpoint == 'mock' }
229
127
  end
230
128
  end
231
129
  end
@@ -3,6 +3,12 @@
3
3
  # Not named test_*.rb on purpose: the Rakefile test pattern
4
4
  # ('test/**/test_*.rb') must not collect this file.
5
5
  #
6
+ # Fake-client FACTORIES live in TestClients; the static recorded payloads
7
+ # and their loader live in TestFixtures (support/fixtures.rb). All factory
8
+ # helpers keep their historical names and signatures, moved verbatim from
9
+ # the TestFixtures module they used to live in, so call sites only change
10
+ # the receiver.
11
+ #
6
12
  # Each fake wraps one provider SDK client class. They all share:
7
13
  # * a response list replayed in order (last entry repeats when exhausted)
8
14
  # * `.calls` recording every parameters hash for assertions
@@ -110,29 +116,32 @@ class FakeBedrockClient
110
116
  end
111
117
  end
112
118
 
113
- module TestFixtures
119
+ # Factory module: builds a fake client pre-loaded with the named fixtures.
120
+ # The helpers keep their historical names, e.g.
121
+ # TestClients.anthropic_client('backends/anthropic_tool_use',
122
+ # 'backends/anthropic')
123
+ # loads each fixture through TestFixtures.fixture and scripts the fake with
124
+ # them in order.
125
+ module TestClients
114
126
  class << self
115
- # Build a fake client pre-loaded with the named fixtures, e.g.
116
- # TestFixtures.openai_client('backends/openai_chat_tool_call',
117
- # 'backends/openai_chat')
118
127
  def openai_client(*names)
119
- FakeOpenAIChatClient.new(*names.collect { |n| fixture(n) })
128
+ FakeOpenAIChatClient.new(*names.collect { |n| TestFixtures.fixture(n) })
120
129
  end
121
130
 
122
131
  def responses_client(*names)
123
- FakeResponsesClient.new(*names.collect { |n| fixture(n) })
132
+ FakeResponsesClient.new(*names.collect { |n| TestFixtures.fixture(n) })
124
133
  end
125
134
 
126
135
  def anthropic_client(*names)
127
- FakeAnthropicClient.new(*names.collect { |n| fixture(n) })
136
+ FakeAnthropicClient.new(*names.collect { |n| TestFixtures.fixture(n) })
128
137
  end
129
138
 
130
139
  def ollama_client(*names)
131
- FakeOllamaClient.new(*names.collect { |n| fixture(n) })
140
+ FakeOllamaClient.new(*names.collect { |n| TestFixtures.fixture(n) })
132
141
  end
133
142
 
134
143
  def bedrock_client(*names)
135
- FakeBedrockClient.new(*names.collect { |n| fixture(n) })
144
+ FakeBedrockClient.new(*names.collect { |n| TestFixtures.fixture(n) })
136
145
  end
137
146
  end
138
147
  end
@@ -2,20 +2,89 @@
2
2
  #
3
3
  # Not named test_*.rb on purpose: the Rakefile test pattern
4
4
  # ('test/**/test_*.rb') must not collect this file.
5
+ #
6
+ # Deliberately free of the production IO abstractions (Path/Open):
7
+ # resolution is plain File math rooted at test/fixtures, every reference is
8
+ # validated before it touches the filesystem, and failures raise
9
+ # FixtureError with a message naming the reference and/or the resolved
10
+ # path. Fake-client factories live in TestClients (support/fake_clients.rb);
11
+ # this module owns only the static recorded payloads.
12
+ #
13
+ # ScoutCoder: Scout::Testing.fixture_root/fixture_path (scout-essentials)
14
+ # were evaluated for the root resolution; they are plain joiners with no
15
+ # traversal rejection, absolute-path rejection or error handling, so the
16
+ # loader is implemented here and the root stays a plain __dir__-relative
17
+ # constant (see tmp/notes/fixture-workstream.md).
5
18
  module TestFixtures
6
19
  FIXTURES_DIR = File.expand_path('../fixtures', __dir__)
7
20
 
21
+ # Raised for invalid fixture references (empty, absolute, `..`
22
+ # traversal, symlink escapes), missing files and invalid JSON. Messages
23
+ # always name the offending reference and/or the resolved path.
24
+ class FixtureError < StandardError; end
25
+
8
26
  class << self
9
27
  # TestFixtures.fixture('backends/openai_chat')
10
28
  # -> parsed JSON from test/fixtures/backends/openai_chat.json
11
- def fixture(name)
12
- path = fixture_path(name)
13
- content = Open.read(path)
14
- JSON.parse(content)
29
+ #
30
+ # `root:` is injectable so the loader tests can exercise the
31
+ # resolution rules against a temporary tree without touching the
32
+ # recorded payloads.
33
+ def fixture(name, root: FIXTURES_DIR)
34
+ path = fixture_path(name, root: root)
35
+
36
+ unless File.file?(path)
37
+ raise FixtureError, "test fixture not found: #{name.inspect} (expected at #{path})"
38
+ end
39
+
40
+ begin
41
+ JSON.parse(File.read(path))
42
+ rescue JSON::ParserError => e
43
+ raise FixtureError, "invalid JSON in test fixture #{path}: #{e.message}"
44
+ end
15
45
  end
16
46
 
17
- def fixture_path(name)
18
- Path.setup(File.join(FIXTURES_DIR, name.to_s + '.json')).find
47
+ # Absolute path of the named fixture ('.json' appended), e.g.
48
+ # TestFixtures.fixture_path('backends/openai_chat').
49
+ #
50
+ # Rejects, before any filesystem access, every reference that is not a
51
+ # plain relative path inside `root`: empty/NUL-bearing strings,
52
+ # absolute paths, and any `..` segment. After resolution an existing
53
+ # target must also sit really (realpath, so symlinks are followed)
54
+ # inside `root`. Does NOT require the file to exist, mirroring the old
55
+ # Path#find semantics; existence is checked by .fixture.
56
+ def fixture_path(name, root: FIXTURES_DIR)
57
+ ref = name.to_s
58
+
59
+ if ref.empty? || ref.include?("\0")
60
+ raise FixtureError, "invalid fixture reference: #{ref.inspect} (root: #{root})"
61
+ end
62
+
63
+ if ref.start_with?(File::SEPARATOR) || ref.match?(%r{\A[A-Za-z]:[\\/]})
64
+ raise FixtureError, "absolute fixture reference rejected: #{ref.inspect} (root: #{root})"
65
+ end
66
+
67
+ if ref.split(File::SEPARATOR).include?('..')
68
+ raise FixtureError, "fixture reference escapes the fixtures root: #{ref.inspect} (root: #{root})"
69
+ end
70
+
71
+ root = File.expand_path(root)
72
+ path = File.expand_path(File.join(root, ref + '.json'))
73
+
74
+ unless path == root || path.start_with?(root + File::SEPARATOR)
75
+ raise FixtureError, "fixture reference escapes the fixtures root: #{ref.inspect} (resolved to #{path})"
76
+ end
77
+
78
+ if File.exist?(path)
79
+ real_root = File.realpath(root)
80
+ real = File.realpath(path)
81
+ unless real == real_root || real.start_with?(real_root + File::SEPARATOR)
82
+ raise FixtureError,
83
+ "fixture path escapes the fixtures root through a symlink: #{ref.inspect} (resolved to #{real})"
84
+ end
85
+ end
86
+
87
+ path
19
88
  end
20
89
  end
21
90
  end
@@ -116,7 +116,15 @@ module LLM
116
116
  id: info[:id] || info[:call_id] || "call_#{@index}" }
117
117
  end
118
118
 
119
- new_calls = LLM.process_calls(tool_definitions, script_calls, &block).flatten
119
+ # ScoutCoder: the real backends thread the caller's save_file
120
+ # into process_calls (Backend::ClassMethods#process_response,
121
+ # default.rb: save_file = options[:save_file]; LLM.process_calls(
122
+ # ..., save_file: save_file, &block)) so the <base>.jobs sidecar
123
+ # and per-round saves work during tool rounds; the mock must do
124
+ # the same or tool-round probes/tests silently lose both.
125
+ new_calls = LLM.process_calls(tool_definitions, script_calls,
126
+ save_file: options[:save_file],
127
+ request_context: options[:request_context], &block).flatten
120
128
  tool_calls.concat new_calls
121
129
  # next round sees the original messages plus the tool call
122
130
  # round, exactly like Backend#chain_tools does