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,213 @@
1
+ require File.expand_path(__FILE__).sub(%r(/test/.*), '/test/test_helper.rb')
2
+ require 'scout/llm/chat'
3
+ require 'json'
4
+ require 'open3'
5
+ require 'rbconfig'
6
+ require 'timeout'
7
+ require 'tmpdir'
8
+ require_relative 'agent_meta_fixtures'
9
+ require_relative 'prov_plot_fixtures'
10
+
11
+ # Explanatory provenance plot tests (`--dot` / `--plot`).
12
+ #
13
+ # These are `scout-ai llm prov --dot` output tests, NOT dot-syntax tests:
14
+ # every assertion below runs against the dot source the CLI writes, so the
15
+ # assertions grep the CLI's own strings (label=, tooltip=, class=) and not a
16
+ # graphviz rendering (except the two graphviz runs, which skip when the dot
17
+ # binary is missing).
18
+ #
19
+ # The fixture is the explanatory mirror (root chat, 6 delegated
20
+ # Cortex/continue jobs, one continuation chain of 3, one error job, 3
21
+ # society chats); see ProvPlotFixtures#explanatory_fixture.
22
+ class TestProvExplanatoryPlot < Test::Unit::TestCase
23
+ include AgentMetaFixtures
24
+ include ProvPlotFixtures
25
+
26
+ REPO_ROOT = File.expand_path('../../../..', __dir__)
27
+
28
+ def self.startup
29
+ Log.severity = 5
30
+ end
31
+
32
+ def prov(*args)
33
+ cmd = [RbConfig.ruby, '-I', File.join(REPO_ROOT, 'lib'),
34
+ File.join(REPO_ROOT, 'bin', 'scout-ai'), 'llm', 'prov',
35
+ '--nocolor', *args.collect(&:to_s)]
36
+ Open3.capture3(*cmd)
37
+ end
38
+
39
+ def dot_for(root)
40
+ @prov_count += 1
41
+ dot_file = File.join(@dir, "prov_#{@prov_count}.dot")
42
+ out, err, status = prov('--dot', dot_file, root)
43
+ assert status.success?, err
44
+ [File.read(dot_file), out]
45
+ end
46
+
47
+ setup do
48
+ @prov_count = 0
49
+ @dir = Dir.mktmpdir('prov-plot')
50
+ end
51
+
52
+ teardown do
53
+ FileUtils.remove_entry @dir if @dir && File.directory?(@dir)
54
+ end
55
+
56
+ test 'labels carry names, paths only in tooltips' do
57
+ TmpFile.with_dir do |dir|
58
+ fx = explanatory_fixture(dir); root = fx[:root]
59
+ dot, = dot_for(root)
60
+ node_lines = dot.lines.grep(/^\s+n\d+ \[/)
61
+ labels = node_lines.flat_map { |l| l.scan(/label=("(?:[^"\\]|\\.)*")/) }
62
+ assert_equal 15, node_lines.length, dot
63
+ assert labels.length >= 15, dot
64
+ # Packet item 1 vs item 8 tension, resolved narrowly: the jobname
65
+ # label itself is `Cortex/continue <name>`, whose slash is the
66
+ # workflow/task separator required by the legacy jobname tests, not
67
+ # a filesystem path. A NAME such as the basename `Worker.chat` is
68
+ # legitimate label content. What must NOT appear is any path: the
69
+ # fixture dir, a `.files/` or `agent.society` fragment, or a second
70
+ # slash beyond the one workflow/task separator.
71
+ labels.each do |label|
72
+ assert_not_include label, dir, "label leaks the fixture dir: #{label}"
73
+ assert_not_include label, '.files/', "label leaks a files dir: #{label}"
74
+ assert_not_include label, 'agent.society', "label leaks a society path: #{label}"
75
+ next unless label.include?('/')
76
+ assert_match(/\A"(?:[^"\/]|\\.)*\/(?:[^"\/]|\\.)*"\z/, label,
77
+ "label carries more than the workflow/task slash: #{label}")
78
+ end
79
+ tooltips = dot.scan(/tooltip=("(?:[^"\\]|\\.)*")/).flatten
80
+ assert_equal labels.length, tooltips.length
81
+ tooltips.each { |t| assert t.include?('/'), "tooltip without full path: #{t}" }
82
+ end
83
+ end
84
+
85
+ test 'root tooltip is the chat, root label names the kind' do
86
+ TmpFile.with_dir do |dir|
87
+ fx = explanatory_fixture(dir); root = fx[:root]
88
+ dot, = dot_for(root)
89
+ root_line = dot.lines.find { |l| l.include?("tooltip=#{root.inspect}") }
90
+ assert root_line, dot
91
+ assert_include root_line, 'Root conversation'
92
+ assert_include root_line, 'root.chat'
93
+ assert_match(/\{rank=source; n\d+;\}/, dot)
94
+ # the rank=source id must be the root node id
95
+ root_id = root_line[/^\s*(n\d+) \[/, 1]
96
+ assert dot.include?("{rank=source; #{root_id};}"), dot
97
+ end
98
+ end
99
+
100
+ test 'worker chat tooltips show the files dir' do
101
+ TmpFile.with_dir do |dir|
102
+ fx = explanatory_fixture(dir); root = fx[:root]; jobs = fx[:jobs]
103
+ dot, = dot_for(root)
104
+ first_turn = jobs[:smoke][0]
105
+ worker = File.join(first_turn + '.files', 'Worker.chat')
106
+ assert_include dot, "tooltip=#{worker.inspect}"
107
+ end
108
+ end
109
+
110
+ test 'semantic edge labels replace machine relations' do
111
+ TmpFile.with_dir do |dir|
112
+ fx = explanatory_fixture(dir); root = fx[:root]
113
+ dot, = dot_for(root)
114
+ assert_equal 6, dot.scan(/label="delegates"/).length, dot
115
+ assert_equal 5, dot.scan(/label="produces"/).length, dot
116
+ assert_equal 2, dot.scan(/label="continues"/).length, dot
117
+ # machine relation tokens survive only as class attributes
118
+ %w[delegated_result dependency].each do |token|
119
+ assert_not_include dot, %(label="#{token}")
120
+ assert dot.include?(%(class="#{token}")), dot
121
+ end
122
+ end
123
+ end
124
+
125
+ test 'continuation chain arcs follow mtime order' do
126
+ TmpFile.with_dir do |dir|
127
+ fx = explanatory_fixture(dir); root = fx[:root]; jobs = fx[:jobs]
128
+ dot, = dot_for(root)
129
+ id_of = {}
130
+ dot.lines.each do |line|
131
+ next unless line =~ /^\s*(n\d+) \[.*tooltip=("(?:[^"\\]|\\.)*")/
132
+ id_of[JSON.parse(Regexp.last_match(2))] = Regexp.last_match(1)
133
+ end
134
+ turn1, turn2, turn3 = jobs[:smoke]
135
+ assert_equal 2, dot.scan(/constraint=false, tailport=s, headport=n/).length, dot
136
+ assert dot.include?("#{id_of[turn1]} -> #{id_of[turn2]} [label=\"continues\""), dot
137
+ assert dot.include?("#{id_of[turn2]} -> #{id_of[turn3]} [label=\"continues\""), dot
138
+ # turn numbering is visible on the smoke labels
139
+ assert_include dot, 'cortex-smoke · turn 1'
140
+ assert_include dot, 'cortex-smoke · turn 2'
141
+ assert_include dot, 'cortex-smoke · turn 3'
142
+ end
143
+ end
144
+
145
+ test 'error outcome replaces token line' do
146
+ TmpFile.with_dir do |dir|
147
+ fx = explanatory_fixture(dir); root = fx[:root]; jobs = fx[:jobs]
148
+ dot, = dot_for(root)
149
+ bad_line = dot.lines.find { |l| l.include?("tooltip=#{jobs[:bad].inspect}") }
150
+ assert bad_line, dot
151
+ assert_include bad_line, '⚠ error'
152
+ assert_not_include bad_line, 'tokens'
153
+ assert_include bad_line, '#FBE3E3'
154
+ assert_include bad_line, 'prov-error'
155
+ end
156
+ end
157
+
158
+ test 'society chats keep pair labels with dashed unlabeled edges' do
159
+ TmpFile.with_dir do |dir|
160
+ fx = explanatory_fixture(dir); root = fx[:root]; society = fx[:society]
161
+ dot, = dot_for(root)
162
+ society.each do |chat|
163
+ line = dot.lines.find { |l| l.include?("tooltip=#{chat.inspect}") }
164
+ assert line, "#{chat}\n#{dot}"
165
+ pair = chat.split(File::SEPARATOR)[-3, 2] * '/'
166
+ assert_include line, "society #{pair}"
167
+ end
168
+ dashed = dot.lines.select { |l| l.include?('style=dashed') }
169
+ assert_equal 3, dashed.length, dot
170
+ dashed.each { |l| assert_not_include l, 'label=' }
171
+ end
172
+ end
173
+
174
+ test 'legacy shape contract and jobname labels survive' do
175
+ TmpFile.with_dir do |dir|
176
+ fx = explanatory_fixture(dir); root = fx[:root]
177
+ dot, = dot_for(root)
178
+ shapes = dot.scan(/^\s+n\d+ \[shape=(\w+)/).flatten
179
+ assert shapes.all? { |shape| %w[box note].include?(shape) }, dot
180
+ assert_equal 15, shapes.length, dot
181
+ assert_include dot, 'Cortex/continue echo-worker'
182
+ assert_include dot, 'Cortex/continue cortex-unknown-brief'
183
+ end
184
+ end
185
+
186
+ test 'graphviz renders the dot without error' do
187
+ TmpFile.with_dir do |dir|
188
+ fx = explanatory_fixture(dir); root = fx[:root]
189
+ dot_file = File.join(dir, 'prov.dot')
190
+ prov('--dot', dot_file, root)
191
+ skip 'graphviz dot not installed' unless Open.exists?('/usr/bin/dot')
192
+ out, err, status = Open3.capture3('dot', '-Tsvg', dot_file)
193
+ assert status.success?, err
194
+ assert out.start_with?('<?xml'), out[0, 100]
195
+ titles = out.scan(/<title>/).length
196
+ assert titles >= 15, out
197
+ end
198
+ end
199
+
200
+ test 'plot writes an svg of bounded natural width' do
201
+ TmpFile.with_dir do |dir|
202
+ fx = explanatory_fixture(dir); root = fx[:root]
203
+ plot_file = File.join(dir, 'prov.svg')
204
+ out, err, status = prov('--plot', plot_file, root)
205
+ assert status.success?, err
206
+ assert File.file?(plot_file), out
207
+ svg = File.read(plot_file)
208
+ width = svg[/width="([\d.]+)pt"/, 1].to_f
209
+ assert width > 0, svg[0, 200]
210
+ assert_operator width, :<=, 1200, "natural width #{width}pt too wide"
211
+ end
212
+ end
213
+ end
@@ -0,0 +1,355 @@
1
+ require File.expand_path(__FILE__).sub(%r(/test/.*), '/test/test_helper.rb')
2
+ require 'scout/llm/chat'
3
+ require 'json'
4
+ require 'open3'
5
+ require 'rbconfig'
6
+ require 'timeout'
7
+ require 'tmpdir'
8
+ require_relative 'agent_meta_fixtures'
9
+ require_relative 'prov_plot_fixtures'
10
+
11
+ # Execution-timeline tests (`--timeline`) for `scout-ai llm prov`.
12
+ #
13
+ # Companion class to TestProvExplanatoryPlot (same file convention, same
14
+ # CLI driver): these assert on the timeline dot the CLI writes through
15
+ # `--timeline FILE.dot`, plus one graphviz geometry check (`dot -Tplain`).
16
+ #
17
+ # The fixture (ProvPlotFixtures#explanatory_fixture) stamps every node
18
+ # with BOTH a chat-content meta `timestamp=` pair and a coherent
19
+ # File.utime (job mtime = end of its chat), so the chat-content priority
20
+ # and the mtime fallback agree on the order. Root and the error job
21
+ # carry no chat timestamps on purpose: they exercise the mtime fallback.
22
+ # Every sequence-dependent expectation below is RECOMPUTED from the
23
+ # fixture's returned `schedule` map, never hard-coded from the spec's
24
+ # ASSUMED sequence.
25
+ class TestProvTimeline < Test::Unit::TestCase
26
+ include AgentMetaFixtures
27
+ include ProvPlotFixtures
28
+
29
+ REPO_ROOT = File.expand_path('../../../..', __dir__)
30
+
31
+ def self.startup
32
+ Log.severity = 5
33
+ end
34
+
35
+ def prov(*args)
36
+ cmd = [RbConfig.ruby, '-I', File.join(REPO_ROOT, 'lib'),
37
+ File.join(REPO_ROOT, 'bin', 'scout-ai'), 'llm', 'prov',
38
+ '--nocolor', *args.collect(&:to_s)]
39
+ Open3.capture3(*cmd)
40
+ end
41
+
42
+ def timeline_for(root, name = 'timeline')
43
+ @prov_count += 1
44
+ target = File.join(@dir, "#{name}_#{@prov_count}.dot")
45
+ out, err, status = prov('--timeline', target, root)
46
+ assert status.success?, err
47
+ [File.read(target), out]
48
+ end
49
+
50
+ # Recompute the expected time sequence from the fixture schedule,
51
+ # exactly as the CLI's time model does (spec S3):
52
+ # job -> chat interval [first meta, last meta] (start = first)
53
+ # job chat -> its own mtime (the fixture stamps end) (start = end)
54
+ # root/bad -> mtime (no chat timestamps) (start = end)
55
+ # society -> its own chat interval (single stamp)
56
+ # Returns [ordered_paths, time_by_path] with [start, end] pairs.
57
+ def expected_sequence(root, jobs, society, schedule)
58
+ time_by_path = {}
59
+ time_by_path[root] = schedule[root]
60
+ time_by_path[jobs[:bad]] = schedule[jobs[:bad]]
61
+ [jobs[:echo], *jobs[:smoke], jobs[:unknown]].each do |job|
62
+ chat = File.join(job + '.files', 'Worker.chat')
63
+ # the job uses the chat interval; the chat NODE uses its own file's
64
+ # chat timestamps too, which for the cumulative replays is
65
+ # [first-turn stamp, own stamp]
66
+ time_by_path[job] = schedule[chat]
67
+ time_by_path[chat] = schedule[chat]
68
+ end
69
+ society.each { |chat| time_by_path[chat] = schedule[chat] }
70
+ # the CLI sorts on the full time key [start, end, path]
71
+ ordered = time_by_path.keys.sort_by { |path| [*time_by_path[path], path] }
72
+ [ordered, time_by_path]
73
+ end
74
+
75
+ # Parse the timeline dot into {node id => {label:, tooltip:, attrs:}}
76
+ # and [[from, to, attrs], ...].
77
+ def parse_dot(dot)
78
+ nodes = {}
79
+ dot.lines.each do |line|
80
+ next unless line =~ /^\s*(n\d+) \[(.*)\];?\s*$/
81
+ id, attrs = Regexp.last_match(1), Regexp.last_match(2)
82
+ label = attrs[/label="((?:[^"\\]|\\.)*)"/, 1]
83
+ tooltip = attrs[/tooltip="((?:[^"\\]|\\.)*)"/, 1]
84
+ nodes[id] = {label: label && label.gsub('\n', "\n"), tooltip: tooltip, attrs: attrs}
85
+ end
86
+ edges = dot.lines.filter_map do |line|
87
+ next unless line =~ /^\s*(n\d+) -> (n\d+) \[(.*)\];?\s*$/
88
+ [Regexp.last_match(1), Regexp.last_match(2), Regexp.last_match(3)]
89
+ end
90
+ [nodes, edges]
91
+ end
92
+
93
+ # Ids are numbered along the sequence, so n0 is the earliest event.
94
+ def id_for_path(nodes, path)
95
+ id, = nodes.find { |_id, node| node[:tooltip] == path }
96
+ raise "no node with tooltip #{path}" unless id
97
+ id
98
+ end
99
+
100
+ setup do
101
+ @prov_count = 0
102
+ @dir = Dir.mktmpdir('prov-timeline')
103
+ end
104
+
105
+ teardown do
106
+ FileUtils.remove_entry @dir if @dir && File.directory?(@dir)
107
+ end
108
+
109
+ test 'T1 rank separation: one event per rank, no rank=same' do
110
+ TmpFile.with_dir do |dir|
111
+ fx = explanatory_fixture(dir); root = fx[:root]; jobs = fx[:jobs]; society = fx[:society]
112
+ dot, = timeline_for(root)
113
+ assert_not_include dot, '{rank=same', dot
114
+ assert_include dot, 'rankdir=TB', dot
115
+ assert_include dot, 'ranksep=0.45', dot
116
+ # the only rank directive is the root pinned to the source rank
117
+ assert_equal 1, dot.scan(/\{rank=source;/).length, dot
118
+ root_id = id_for_path(parse_dot(dot)[0], root)
119
+ assert dot.include?("{rank=source; #{root_id};}"), dot
120
+ # and the root must be the earliest event
121
+ fx2 = explanatory_fixture(dir); schedule2 = fx2[:schedule]
122
+ ordered, = expected_sequence(root, jobs, society, schedule2)
123
+ assert_equal root, ordered.first, dot
124
+ end
125
+ end
126
+
127
+ test 'T2/T3 spine: consecutive time neighbours, reused segments' do
128
+ TmpFile.with_dir do |dir|
129
+ fx = explanatory_fixture(dir); root = fx[:root]; jobs = fx[:jobs]; society = fx[:society]; schedule = fx[:schedule]
130
+ dot, = timeline_for(root)
131
+ nodes, edges = parse_dot(dot)
132
+ ordered, = expected_sequence(root, jobs, society, schedule)
133
+ # the ids ARE the sequence order (n0 = earliest)
134
+ ordered.each_with_index do |path, index|
135
+ assert_equal "n#{index}", id_for_path(nodes, path), "#{path} should be n#{index}"
136
+ end
137
+ # every consecutive pair is joined by exactly one constraint=true edge
138
+ ordered.each_cons(2) do |first, second|
139
+ joined = edges.select { |f, t, attrs| f == id_for_path(nodes, first) && t == id_for_path(nodes, second) && attrs.include?('constraint=true') }
140
+ assert_equal 1, joined.length, "#{first} -> #{second}\n#{dot}"
141
+ end
142
+ # no other edge carries constraint=true
143
+ assert_equal ordered.length - 1, edges.count { |_f, _t, attrs| attrs.include?('constraint=true') }, dot
144
+ end
145
+ end
146
+
147
+ test 'T4 chain integrity: chain arcs follow the time order' do
148
+ TmpFile.with_dir do |dir|
149
+ fx = explanatory_fixture(dir); root = fx[:root]; jobs = fx[:jobs]; society = fx[:society]; schedule = fx[:schedule]
150
+ dot, = timeline_for(root)
151
+ nodes, = parse_dot(dot)
152
+ turns = jobs[:smoke]
153
+ time = {}
154
+ turns.each_with_index { |job, index| time[job] = schedule[job].first }
155
+ ordered_turns = turns.sort_by { |job| [time[job], job] }
156
+ continues = dot.scan(/label="continues"/).length
157
+ assert_equal 2, continues, dot
158
+ (ordered_turns[0...-1]).zip(ordered_turns[1..-1]).each do |first, second|
159
+ assert dot.include?("#{id_for_path(nodes, first)} -> #{id_for_path(nodes, second)} [label=\"continues\""), dot
160
+ end
161
+ end
162
+ end
163
+
164
+ test 'T5 ports: delegates headport=w, continues tailport=e headport=w' do
165
+ TmpFile.with_dir do |dir|
166
+ fx = explanatory_fixture(dir); root = fx[:root]; jobs = fx[:jobs]
167
+ dot, = timeline_for(root)
168
+ assert dot.scan(/class="delegated_result"[^\]]*headport=w/).length +
169
+ dot.scan(/headport=w[^\]]*class="delegated_result"/).length >= 6, dot
170
+ assert_equal 2, dot.scan(/constraint=false, tailport=e, headport=w/).length, dot
171
+ assert_not_include dot, 'tailport=s'
172
+ assert_not_include dot, 'headport=n'
173
+ end
174
+ end
175
+
176
+ test 'T6 error job: time line present, token line absent' do
177
+ TmpFile.with_dir do |dir|
178
+ fx = explanatory_fixture(dir); root = fx[:root]; jobs = fx[:jobs]
179
+ dot, = timeline_for(root)
180
+ bad = dot.lines.find { |l| l.include?("tooltip=#{jobs[:bad].inspect}") }
181
+ assert bad, dot
182
+ assert_include bad, 't='
183
+ assert_include bad, '⚠ error'
184
+ assert_not_include bad, 'tokens'
185
+ assert_include bad, 'prov-error'
186
+ end
187
+ end
188
+
189
+ test 'T7 cluster rule: chain cluster iff contiguous, no society cluster' do
190
+ TmpFile.with_dir do |dir|
191
+ fx = explanatory_fixture(dir); root = fx[:root]; jobs = fx[:jobs]; society = fx[:society]; schedule = fx[:schedule]
192
+ dot, = timeline_for(root)
193
+ nodes, = parse_dot(dot)
194
+ assert_not_include dot, 'cluster_society', dot
195
+ assert_include dot, 'cortex-smoke continuation chain', dot
196
+ # recomputed contiguity: the chain cluster appears iff the chain's
197
+ # jobs + produced chats form a contiguous block of the sequence
198
+ ordered, = expected_sequence(root, jobs, society, schedule)
199
+ smoke = [jobs[:smoke], jobs[:smoke].collect { |j| File.join(j + '.files', 'Worker.chat') }].flatten
200
+ indexes = smoke.collect { |path| ordered.index(path) }.compact.sort
201
+ contiguous = indexes.each_cons(2).all? { |a, b| b == a + 1 }
202
+ cluster_blocks = dot.scan(/subgraph cluster_cortex_smoke \{.*?\n \}/m)
203
+ if contiguous
204
+ assert_equal 1, cluster_blocks.length, dot
205
+ ids_in_cluster = cluster_blocks[0].scan(/n\d+/)
206
+ smoke.each { |path| assert_include ids_in_cluster, id_for_path(nodes, path), dot }
207
+ assert_equal smoke.length, ids_in_cluster.length, dot
208
+ else
209
+ assert cluster_blocks.empty?, dot
210
+ end
211
+ end
212
+ end
213
+
214
+ test 'T9 y-monotonic order via dot -Tplain' do
215
+ TmpFile.with_dir do |dir|
216
+ fx = explanatory_fixture(dir); root = fx[:root]; jobs = fx[:jobs]; society = fx[:society]; schedule = fx[:schedule]
217
+ dot_file = File.join(dir, 'timeline.dot')
218
+ prov('--timeline', dot_file, root)
219
+ dot = File.read(dot_file)
220
+ skip 'graphviz dot not installed' unless Open.exists?('/usr/bin/dot')
221
+ plain, err, status = Open3.capture3('dot', '-Tplain', dot_file)
222
+ assert status.success?, err
223
+ ordered, = expected_sequence(root, jobs, society, schedule)
224
+ nodes, = parse_dot(dot)
225
+ # -Tplain has a bottom-left origin, so EARLIER events must have
226
+ # LARGER y coordinates (monotone non-increasing down the sequence).
227
+ y_by_path = {}
228
+ plain.lines.each do |line|
229
+ next unless line =~ /^node (n\d+) [\d.]+ ([\d.]+)/
230
+ y_by_path[Regexp.last_match(1)] = Regexp.last_match(2).to_f
231
+ end
232
+ ys = ordered.collect { |path| y_by_path[id_for_path(nodes, path)] }
233
+ ys.each_cons(2) { |first, second| assert_operator first, :>=, second, "y not monotone: #{ys.inspect}" }
234
+ end
235
+ end
236
+
237
+ test 'T10 badges and time lines match the computed order' do
238
+ TmpFile.with_dir do |dir|
239
+ fx = explanatory_fixture(dir); root = fx[:root]; jobs = fx[:jobs]; society = fx[:society]; schedule = fx[:schedule]
240
+ dot, = timeline_for(root)
241
+ nodes, = parse_dot(dot)
242
+ # root: mtime fallback => point badge `t=` without arrow
243
+ root_line = nodes[id_for_path(nodes, root)][:label]
244
+ assert root_line.lines[1] =~ /^t=\d\d:\d\d:\d\d$/, root_line
245
+ # stamped nodes: interval badge with duration
246
+ turn3 = File.join(jobs[:smoke][2] + '.files', 'Worker.chat')
247
+ label = nodes[id_for_path(nodes, turn3)][:label]
248
+ assert label.lines[1] =~ /^t=\d\d:\d\d:\d\d→\d\d:\d\d:\d\d · \d+s$/, label
249
+ # every visible node carries exactly one time line
250
+ nodes.each_value do |node|
251
+ time_lines = node[:label].lines.count { |l| l =~ /^t=/ }
252
+ assert_equal 1, time_lines, node[:label]
253
+ end
254
+ # timestamps only in the time line: no absolute paths in labels
255
+ nodes.each_value do |node|
256
+ assert_not_include node[:label], dir, node[:label]
257
+ assert_not_include node[:label], '.files/', node[:label]
258
+ assert_not_include node[:label], 'agent.society', node[:label]
259
+ end
260
+ end
261
+ end
262
+
263
+ test 'T11 tooltips carry full paths, labels carry none' do
264
+ TmpFile.with_dir do |dir|
265
+ fx = explanatory_fixture(dir); root = fx[:root]; jobs = fx[:jobs]; society = fx[:society]
266
+ dot, = timeline_for(root)
267
+ nodes, = parse_dot(dot)
268
+ assert_equal 15, nodes.length, dot
269
+ nodes.each_value do |node|
270
+ assert node[:tooltip]&.include?('/'), node.inspect
271
+ assert_not_include node[:label], dir, node[:label]
272
+ assert_not_include node[:label], '.files/', node[:label]
273
+ assert_not_include node[:label], 'agent.society', node[:label]
274
+ next unless node[:label].include?('/')
275
+ assert_match(/\A(?:[^"\/]|\\.)*\/(?:[^"\/]|\\.)*\z/m, node[:label], node[:label])
276
+ end
277
+ # every fixture node (root, jobs, produced chats, society chats) has
278
+ # its own node with its own tooltip
279
+ expected = [root, jobs[:echo], jobs[:unknown], jobs[:bad], *jobs[:smoke],
280
+ *society,
281
+ *[jobs[:echo], jobs[:unknown], *jobs[:smoke]].collect { |j| File.join(j + '.files', 'Worker.chat') }]
282
+ tooltips = nodes.values.collect { |node| node[:tooltip] }
283
+ expected.each { |path| assert_include tooltips, path }
284
+ end
285
+ end
286
+
287
+ test 'T12 render: --timeline svg produces a renderable document' do
288
+ TmpFile.with_dir do |dir|
289
+ fx = explanatory_fixture(dir); root = fx[:root]
290
+ svg_file = File.join(dir, 'timeline.svg')
291
+ out, err, status = prov('--timeline', svg_file, root)
292
+ assert status.success?, err
293
+ assert File.file?(svg_file), out
294
+ svg = File.read(svg_file)
295
+ assert svg.start_with?('<?xml'), svg[0, 100]
296
+ assert_operator svg.scan(/<title>/).length, :>=, 15, svg[0, 400]
297
+ end
298
+ end
299
+
300
+ test 'T13 budgets: no rank=same, bounded natural width' do
301
+ TmpFile.with_dir do |dir|
302
+ fx = explanatory_fixture(dir); root = fx[:root]
303
+ svg_file = File.join(dir, 'timeline.svg')
304
+ prov('--timeline', svg_file, root)
305
+ skip 'graphviz dot not installed' unless Open.exists?('/usr/bin/dot')
306
+ svg = File.read(svg_file)
307
+ width = svg[/width="([\d.]+)pt"/, 1].to_f
308
+ assert_operator width, :<=, 900, "natural width #{width}pt too wide for a single column"
309
+ height = svg[/height="([\d.]+)pt"/, 1].to_f
310
+ assert_operator height, :>, 200, height
311
+ end
312
+ end
313
+
314
+ test 'T14 census: exact node/edge class census' do
315
+ TmpFile.with_dir do |dir|
316
+ fx = explanatory_fixture(dir); root = fx[:root]; jobs = fx[:jobs]; society = fx[:society]; schedule = fx[:schedule]
317
+ dot, = timeline_for(root)
318
+ nodes, edges = parse_dot(dot)
319
+ # node class census, counted by parsing the class attribute rather
320
+ # than by substring so prov-overlap flags do not double-count
321
+ classes = nodes.values.collect { |node| node[:attrs][/class="([^"]*)"/, 1] }
322
+ assert_equal 15, nodes.length, dot
323
+ assert_equal 6, classes.count { |c| c.include?('prov-job') }, classes.inspect
324
+ assert_equal 1, classes.count { |c| c.include?('prov-error') }, classes.inspect
325
+ assert_equal 1, classes.count { |c| c.include?('prov-root') }, classes.inspect
326
+ assert_equal 3, classes.count { |c| c.include?('prov-society') }, classes.inspect
327
+ assert_equal 5, classes.count { |c| c.include?('prov-chat') && !c.include?('prov-society') }, classes.inspect
328
+ # label census: only continues arcs carry labels
329
+ assert_equal 2, dot.scan(/label="continues"/).length, dot
330
+ assert_equal 0, dot.scan(/label="delegates"/).length, dot
331
+ assert_equal 0, dot.scan(/label="produces"/).length, dot
332
+ assert_equal 0, dot.scan(/label="result"/).length, dot
333
+ # spine census: 14 consecutive pairs, one constraint=true each
334
+ ordered, time_by_path = expected_sequence(root, jobs, society, schedule)
335
+ assert_equal ordered.length - 1, edges.count { |_f, _t, a| a.include?('constraint=true') }, dot
336
+ # synthetic spine segments carry the timeline class
337
+ synthetic = dot.scan(/class="timeline"/).length
338
+ assert_operator synthetic, :>=, 1, dot
339
+ # overlap flags recomputed from the same time keys the CLI uses
340
+ # (job key = its chat interval, chat node key = its own interval,
341
+ # fallback nodes are points); [start,end) pairwise overlap.
342
+ expected_overlap = ordered.select do |path|
343
+ span = time_by_path[path]
344
+ ordered.any? do |other|
345
+ next false if other == path
346
+ other_span = time_by_path[other]
347
+ span.first < other_span.last && other_span.first < span.last
348
+ end
349
+ end
350
+ flagged = nodes.count { |_id, node| node[:attrs].include?('prov-overlap') }
351
+ assert_equal expected_overlap.length, flagged,
352
+ "expected #{expected_overlap.collect { |p| File.basename(p) }.inspect}"
353
+ end
354
+ end
355
+ end