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
@@ -45,8 +45,8 @@ class TestChatAgentMetaTokens < Test::Unit::TestCase
45
45
  .sort_by { |event| event[:inference_id] }
46
46
  .collect { |event| event[:evidence].first }
47
47
 
48
- assert_equal [parent, 2, :agent_meta, 0], evidence.first[:evidence_address]
49
- assert_equal [parent, 2, :agent_meta, 1], evidence.last[:evidence_address]
48
+ assert_equal [parent, 2, :meta, 0], evidence.first[:evidence_address]
49
+ assert_equal [parent, 2, :meta, 1], evidence.last[:evidence_address]
50
50
  assert_equal %w[a1 a1], evidence.collect { |record| record[:call_id] }
51
51
  assert_equal %w[ask ask], evidence.collect { |record| record[:tool_name] }
52
52
  assert_equal parent, evidence.first[:source]
@@ -112,8 +112,8 @@ class TestChatAgentMetaTokens < Test::Unit::TestCase
112
112
 
113
113
  chat_side = event[:evidence].find { |record| record[:origin] == :chat_meta }
114
114
  receipt_side = event[:evidence].find { |record| record[:origin] == :agent_meta }
115
- assert_equal File.join(worker + '.files', 'log', 'agent.chat'), chat_side[:source]
116
- assert_equal [parent, 2, :agent_meta, event[:inference_id] == 'w1' ? 0 : 1],
115
+ assert_equal File.join(worker + '.files', 'agent.chat'), chat_side[:source]
116
+ assert_equal [parent, 2, :meta, event[:inference_id] == 'w1' ? 0 : 1],
117
117
  receipt_side[:evidence_address]
118
118
  assert !event[:conflict]
119
119
  end
@@ -451,7 +451,7 @@ class TestChatAgentMetaTokens < Test::Unit::TestCase
451
451
 
452
452
  unresolved = warnings.last
453
453
  assert_equal missing, unresolved[:reference]
454
- assert_equal [chat, 4, :agent_meta, 0], unresolved[:evidence_address]
454
+ assert_equal [chat, 4, :meta, 0], unresolved[:evidence_address]
455
455
  assert_equal 'b2', unresolved[:call_id]
456
456
  assert_match(/unresolved_job_reference/, unresolved[:message])
457
457
  end
@@ -496,8 +496,8 @@ class TestChatAgentMetaTokens < Test::Unit::TestCase
496
496
  chat_side = event[:evidence].select { |record| record[:origin] == :chat_meta }
497
497
  assert_equal 3, chat_side.length
498
498
  expected_sources = [parent,
499
- File.join(j1 + '.files', 'log', 'agent.chat'),
500
- File.join(j2 + '.files', 'log', 'agent.chat')].collect(&:to_s).sort
499
+ File.join(j1 + '.files', 'agent.chat'),
500
+ File.join(j2 + '.files', 'agent.chat')].collect(&:to_s).sort
501
501
  assert_equal expected_sources, chat_side.collect { |record| record[:source].to_s }.sort
502
502
 
503
503
  receipt_side = event[:evidence].select { |record| record[:origin] == :agent_meta }
@@ -545,7 +545,7 @@ class TestChatAgentMetaTokens < Test::Unit::TestCase
545
545
  # The cumulative log remains fully inspectable: its direct totals still
546
546
  # count 3 + 2 events (30 + 200 = 230), and the traversal still reaches
547
547
  # it through the ordinary :log relation.
548
- log_path = File.join(b + '.files', 'log', 'agent.chat')
548
+ log_path = File.join(b + '.files', 'agent.chat')
549
549
  assert_equal({pt: 230, ct: 0, tt: 230, cct: 0, cwt: 0, rt: 0},
550
550
  Chat.token_totals([Chat.load(log_path)]),
551
551
  'the history itself is untouched and readable')
@@ -636,6 +636,57 @@ class TestChatAgentMetaTokens < Test::Unit::TestCase
636
636
 
637
637
  ## Scope validation
638
638
 
639
+ ## Round-2 pins (bout 1): blank-string identifiers are treated as absent
640
+
641
+ # A blank `inference_id=""` is not selected as a shared token identity when
642
+ # a real identifier exists elsewhere for the same evidence group: the blank
643
+ # is not truthy evidence of identity. Pinned BEFORE the tokens.rb fix
644
+ # (truthiness checks at ~193-203 let Ruby's truthy "" win).
645
+ def test_blank_inference_id_is_not_selected_as_identity
646
+ TmpFile.with_dir do |dir|
647
+ worker = make_job(dir, 'W/ask/Default_w',
648
+ logs: {'agent.chat' => "user: w\nmeta: pt=11 ct=7 tt=18 inference_id=\nassistant: done\n"})
649
+ parent = write_chat(dir, 'parent.chat',
650
+ receipt_chat_text(
651
+ {'a1' => [meta_receipt('pt=11 ct=7 tt=18 inference_id=')]}
652
+ ))
653
+
654
+ events = Chat.provenance_token_events(parent)
655
+
656
+ # The two evidence records are the SAME inference (equal token facts in
657
+ # the log and the receipt), so with blanks treated as absent the group
658
+ # resolves to the worker's lineage identity; selecting the blank string
659
+ # would key both records under [:inference_id, ""] and merge DISTINCT
660
+ # inferences that happen to share the blank.
661
+ assert events.none? { |event| event[:identity] == [:inference_id, ''] },
662
+ 'blank inference_id must never become the shared identity key'
663
+ end
664
+ end
665
+
666
+ # A blank `provider_response_id` likewise never serves as identity: two
667
+ # legacy chat-side metas in different logs (no inference_id at all, so the
668
+ # lineage rule would give them distinct identities) must not collapse onto
669
+ # one [:provider_response_id, ""] event. Pinned BEFORE the fix.
670
+ def test_blank_provider_response_id_does_not_merge_distinct_inferences
671
+ TmpFile.with_dir do |dir|
672
+ j1 = make_job(dir, 'J1/ask/Default_1',
673
+ logs: {'agent.chat' => "user: a\nmeta: pt=5 tt=6 provider_response_id=\nassistant: done\n"})
674
+ j2 = make_job(dir, 'J2/ask/Default_2',
675
+ logs: {'agent.chat' => "user: b\nmeta: pt=7 tt=8 provider_response_id=\nassistant: done\n"})
676
+ copied = write_chat(dir, 'copied.chat',
677
+ "user: go\nmeta: job=#{j1}\nmeta: job=#{j2}\nassistant: done\n")
678
+
679
+ events = Chat.provenance_token_events(copied)
680
+
681
+ assert_equal 2, events.length,
682
+ 'two distinct inferences must stay two events when their only provider_response_id is blank'
683
+ assert events.none? { |event| event[:identity] == [:provider_response_id, ''] },
684
+ 'blank provider_response_id must never become the shared identity key'
685
+ assert_equal({pt: 12, ct: 0, tt: 14, cct: 0, cwt: 0, rt: 0},
686
+ Chat.provenance_token_totals(copied))
687
+ end
688
+ end
689
+
639
690
  def test_unknown_scope_raises
640
691
  TmpFile.with_dir do |dir|
641
692
  path = write_chat(dir, 'any.chat', "user: hi\nassistant: done\n")
@@ -0,0 +1,178 @@
1
+ require File.expand_path(__FILE__).sub(%r(/test/.*), '/test/test_helper.rb')
2
+ require 'scout/llm/agent'
3
+
4
+ class TestLLMChatAgentView < Test::Unit::TestCase
5
+ # Same private workflow directory trick as TestLLMChatLiveWorkload:
6
+ # Workflow.directory is reassigned by the shared setup in test_helper,
7
+ # so point it lazily from the test bodies.
8
+ def wfdir
9
+ @wfdir ||= begin
10
+ dir = Path.setup(Workflow.directory['agent-view-wf'])
11
+ Workflow.directory = dir
12
+ dir
13
+ end
14
+ end
15
+
16
+ def agent_file
17
+ @agent_file ||= begin
18
+ sf = tmpdir['agent-view'].find + '.chat'
19
+ Open.rm_rf sf
20
+ FileUtils.mkdir_p(File.dirname(sf))
21
+ FileUtils.touch(sf)
22
+ sf
23
+ end
24
+ end
25
+
26
+ def write_info(short_path, status, pid, type: 'string')
27
+ dir = wfdir[short_path].find
28
+ Open.rm_rf dir
29
+ FileUtils.mkdir_p(dir)
30
+ File.write(dir + '.info',
31
+ JSON.dump({status: status, pid: pid, type: type,
32
+ workflow: short_path.split('/').first,
33
+ task_name: short_path.split('/')[1]}))
34
+ dir
35
+ end
36
+
37
+ def write_agent_chat(*messages)
38
+ Open.rm_rf agent_file
39
+ Open.write(agent_file, Chat.print(messages))
40
+ agent_file
41
+ end
42
+
43
+ def dispatching_chat
44
+ write_agent_chat({role: 'user', content: 'go'},
45
+ {role: 'meta', content: 'job=WF/ask/one'})
46
+ end
47
+
48
+ def test_trailing_user_message_is_active_dispatched
49
+ write_agent_chat({role: 'user', content: 'go'})
50
+ activity = Chat.agent_log_activity(agent_file)
51
+ assert activity[:active]
52
+ assert_equal :dispatched, activity[:reason]
53
+ assert_equal 'user', activity[:last_role]
54
+ assert_equal 1, activity[:message_count]
55
+ assert_equal 0, activity[:rounds]
56
+ end
57
+
58
+ def test_trailing_function_call_without_output_is_tool_round_in_flight
59
+ write_agent_chat({role: 'user', content: 'go'},
60
+ {role: 'assistant', content: 'hm'},
61
+ {role: 'function_call', content: {name: 'slow', arguments: {}, id: 'c1'}.to_json})
62
+ activity = Chat.agent_log_activity(agent_file)
63
+ assert activity[:active]
64
+ assert_equal :tool_round_in_flight, activity[:reason]
65
+ assert_equal 1, activity[:rounds]
66
+ end
67
+
68
+ def test_trailing_function_call_output_is_next_round_pending
69
+ write_agent_chat({role: 'user', content: 'go'},
70
+ {role: 'function_call', content: {name: 'slow', arguments: {}, id: 'c1'}.to_json},
71
+ {role: 'function_call_output', content: 'slow done'})
72
+ activity = Chat.agent_log_activity(agent_file)
73
+ assert activity[:active]
74
+ assert_equal :next_round_pending, activity[:reason]
75
+ assert_equal 'function_call_output', activity[:last_role]
76
+ end
77
+
78
+ def test_trailing_assistant_without_open_call_is_idle
79
+ write_agent_chat({role: 'user', content: 'go'},
80
+ {role: 'assistant', content: 'done'},
81
+ {role: 'meta', content: 'job=WF/ask/one'})
82
+ activity = Chat.agent_log_activity(agent_file)
83
+ refute activity[:active]
84
+ assert_equal :idle, activity[:reason]
85
+ # control roles (the trailing meta) are skipped when finding the last
86
+ # conversational message
87
+ assert_equal 'assistant', activity[:last_role]
88
+ assert_equal 1, activity[:rounds]
89
+ end
90
+
91
+ def test_empty_file_and_missing_file_are_inactive
92
+ Open.write(agent_file, '')
93
+ activity = Chat.agent_log_activity(agent_file)
94
+ refute activity[:active]
95
+ assert_equal :no_messages, activity[:reason]
96
+
97
+ activity = Chat.agent_log_activity(agent_file + '.missing')
98
+ refute activity[:active]
99
+ assert_equal :unreadable, activity[:reason]
100
+ end
101
+
102
+ def test_dangling_meta_followed_to_running_job
103
+ write_info('WF/ask/one', 'running', Process.pid, type: 'chat')
104
+ dispatching_chat
105
+ entries = Chat.dangling_agent_job_metas(agent_file, captured: [])
106
+ assert_equal 1, entries.length
107
+ entry = entries.first
108
+ assert_equal :dangling_job, entry[:kind]
109
+ assert_equal 'WF/ask/one', entry[:reference]
110
+ assert_equal :running, entry[:state]
111
+ assert_equal agent_file, entry[:agent_file]
112
+ assert entry[:step].is_a?(Step)
113
+ end
114
+
115
+ def test_dangling_meta_of_finished_job_is_not_reported
116
+ write_info('WF/ask/one', 'done', 999999999, type: 'chat')
117
+ dispatching_chat
118
+ assert_equal [], Chat.dangling_agent_job_metas(agent_file, captured: [])
119
+ end
120
+
121
+ def test_meta_already_captured_is_not_reported_again
122
+ write_info('WF/ask/one', 'running', Process.pid, type: 'chat')
123
+ dispatching_chat
124
+ assert_equal [], Chat.dangling_agent_job_metas(agent_file, captured: ['WF/ask/one'])
125
+ # and by resolved path (the Step form the forensic traversal holds)
126
+ dir = wfdir['WF/ask/one'].find
127
+ assert_equal [], Chat.dangling_agent_job_metas(agent_file, captured: [dir.to_s])
128
+ end
129
+
130
+ def test_agent_view_live_combines_activity_and_dangling_job
131
+ write_info('WF/ask/one', 'running', Process.pid, type: 'chat')
132
+ dispatching_chat
133
+ entries = Chat.agent_view_live(agent_file, captured: [])
134
+ kinds = entries.collect { |e| e[:kind] }
135
+ assert_equal %i(agent_activity dangling_job), kinds.sort
136
+ activity = entries.find { |e| e[:kind] == :agent_activity }
137
+ assert_equal :dispatched, activity[:reason]
138
+ assert_equal agent_file, activity[:agent_file]
139
+ job = entries.find { |e| e[:kind] == :dangling_job }
140
+ assert_equal 'WF/ask/one', job[:reference]
141
+ assert_equal :running, job[:state]
142
+ end
143
+
144
+ def test_agent_view_live_is_empty_when_idle_and_nothing_dangling
145
+ write_info('WF/ask/one', 'done', 999999999, type: 'chat')
146
+ write_agent_chat({role: 'user', content: 'go'},
147
+ {role: 'assistant', content: 'done'})
148
+ assert_equal [], Chat.agent_view_live(agent_file, captured: [])
149
+ end
150
+
151
+ def test_agent_view_live_is_empty_for_missing_file
152
+ assert_equal [], Chat.agent_view_live(agent_file + '.missing', captured: [])
153
+ end
154
+
155
+ # Round-2 pin (bout 1). A log with MULTIPLE outstanding `job=` metas
156
+ # resolves to several dangling entries in agent_view_live, and the
157
+ # per-log fold in live_report must preserve ALL of them (union of the
158
+ # references), not only the first. Pinned BEFORE the round-2 fix.
159
+ def test_multiple_dangling_job_references_are_all_preserved
160
+ write_info('WF/ask/one', 'running', Process.pid, type: 'chat')
161
+ write_info('WF/load/two', 'running', Process.pid, type: 'chat')
162
+ Open.write(agent_file, Chat.print([
163
+ {role: 'user', content: 'go'},
164
+ {role: 'meta', content: 'job=WF/ask/one'},
165
+ {role: 'meta', content: 'job=WF/load/two'}]))
166
+
167
+ view = Chat.agent_view_live(agent_file, captured: [])
168
+ dangling = view.select { |e| e[:kind] == :dangling_job }
169
+ assert_equal %w(WF/ask/one WF/load/two),
170
+ dangling.collect { |e| e[:reference] }.sort,
171
+ 'agent_view_live resolves every outstanding reference'
172
+
173
+ report = Chat.live_report(agent_file, captured: [])
174
+ preserved = report[:entries].collect { |e| e[:reference].to_s }.sort
175
+ assert preserved.include?('WF/ask/one') && preserved.include?('WF/load/two'),
176
+ "per-log fold must preserve ALL outstanding job references, got #{preserved.inspect}"
177
+ end
178
+ end
@@ -0,0 +1,282 @@
1
+ # Tests for the unified live report: Chat.live_report and the dependency
2
+ # expansion helpers (expand_live_jobs / walk_live_job) in
3
+ # lib/scout/llm/chat/provenance.rb.
4
+ #
5
+ # Fixtures are synthetic, in the style of test_live_workload.rb: a job is a
6
+ # directory + `.info` JSON, running is a live pid (this test process).
7
+ # Dependencies are written INTO the `.info` (the same place a real job
8
+ # records them, read back by Step#dependencies) rather than stubbed on an
9
+ # instance, because live_report loads its own Step objects from the paths
10
+ # in the sidecar; an instance stub would never be seen. The cycle/depth
11
+ # tests use the same `.info` mechanism, which lets a real cycle be
12
+ # expressed (real Step#rec_dependencies is cycle-safe by construction;
13
+ # the guards in walk_live_job are the second line of defense).
14
+ require File.expand_path(__FILE__).sub(%r(/test/.*), '/test/test_helper.rb')
15
+ require 'scout/llm/agent'
16
+
17
+ class TestLLMChatLiveReport < Test::Unit::TestCase
18
+ def wfdir
19
+ @wfdir ||= begin
20
+ dir = Path.setup(Workflow.directory['live-report-wf'])
21
+ Workflow.directory = dir
22
+ dir
23
+ end
24
+ end
25
+
26
+ def save_file
27
+ @save_file ||= begin
28
+ sf = tmpdir['agent.chat'].find
29
+ Open.rm_rf sf
30
+ FileUtils.mkdir_p(File.dirname(sf))
31
+ FileUtils.touch(sf)
32
+ sf
33
+ end
34
+ end
35
+
36
+ # Synthetic job directory + `.info`. `deps` lists the job DIRECTORIES
37
+ # this job depends on, exactly like a produced job's info does.
38
+ def write_info(short_path, status, pid, type: 'string', deps: [])
39
+ dir = wfdir[short_path].find
40
+ Open.rm_rf dir
41
+ FileUtils.mkdir_p(dir)
42
+ File.write(dir + '.info',
43
+ JSON.dump({status: status, pid: pid, type: type,
44
+ workflow: short_path.split('/').first,
45
+ task_name: short_path.split('/')[1],
46
+ dependencies: deps}))
47
+ dir
48
+ end
49
+
50
+ def write_sidecar(entries)
51
+ sidecar = Chat.jobs_file(save_file)
52
+ Open.rm_rf sidecar
53
+ File.write(sidecar, entries.join("\n") + "\n")
54
+ sidecar
55
+ end
56
+
57
+ # The chat_task machinery anchors the running agent under <job>.files.
58
+ def write_agent_log(job_short_path, content)
59
+ files_dir = wfdir[job_short_path + '.files'].find
60
+ FileUtils.mkdir_p(files_dir)
61
+ log = File.join(files_dir, 'agent.chat')
62
+ File.write(log, content)
63
+ log
64
+ end
65
+
66
+ def chat_text(*messages)
67
+ "\n" + messages.collect { |m| "#{m[:role]}:\n\n#{m[:content]}" } * "\n\n" + "\n"
68
+ end
69
+
70
+ def test_wrapper_dependency_yields_one_inference_entry
71
+ chat_dir = write_info('WF/continue/one', 'running', Process.pid, type: 'chat')
72
+ write_info('WF/cortex_continue/one', 'running', Process.pid,
73
+ deps: [chat_dir])
74
+ write_agent_log('WF/continue/one', chat_text({role: 'user', content: 'go'}))
75
+ write_sidecar(['WF/cortex_continue/one'])
76
+
77
+ report = Chat.live_report(save_file, captured: [])
78
+ inference = report[:entries].select { |e| e[:kind] == :inference }
79
+ assert_equal 1, inference.length, 'expected exactly one inference entry'
80
+ entry = inference.first
81
+ assert_equal wfdir['WF/continue/one'].find.to_s, entry[:path]
82
+ assert_equal wfdir['WF/continue/one.files/agent.chat'].find.to_s,
83
+ entry[:agent_log], 'expected the agent log path to be attached'
84
+ assert entry[:activity][:active], 'expected activity on the agent log'
85
+ assert_equal [:sidecar], [entry[:source]].flatten.uniq
86
+
87
+ # The wrapper is kept as workload context, never as a second inference.
88
+ wrapper_entries = report[:entries].select do |e|
89
+ e[:path] == wfdir['WF/cortex_continue/one'].find.to_s
90
+ end
91
+ assert wrapper_entries.any? { |e| e[:kind] == :workload_context }
92
+ assert wrapper_entries.all? { |e| e[:kind] == :workload_context }
93
+ end
94
+
95
+ def test_same_job_double_arrival_merges_to_one_entry
96
+ write_info('WF/ask/one', 'running', Process.pid, type: 'chat')
97
+ write_sidecar(['WF/ask/one'])
98
+ # The same job also dangles as an immediate `job=` meta in the agent
99
+ # save file (agent.rb writes it before job.produce).
100
+ Open.write(save_file, chat_text({role: 'user', content: 'go'},
101
+ {role: 'meta', content: 'job=WF/ask/one'}))
102
+
103
+ report = Chat.live_report(save_file, captured: [])
104
+ same = report[:entries].select { |e| e[:path] == wfdir['WF/ask/one'].find.to_s }
105
+ assert_equal 1, same.length, 'same job must yield ONE merged entry'
106
+ sources = [same.first[:source]].flatten
107
+ assert_includes sources, :sidecar
108
+ assert_includes sources, :agent_view
109
+ assert_equal :inference, same.first[:kind]
110
+ end
111
+
112
+ def test_captured_job_is_dropped_in_all_passes
113
+ write_info('WF/ask/one', 'running', Process.pid, type: 'chat')
114
+ write_sidecar(['WF/ask/one'])
115
+ Open.write(save_file, chat_text({role: 'user', content: 'go'},
116
+ {role: 'meta', content: 'job=WF/ask/one'}))
117
+ # A running societal child whose job is captured.
118
+ child = File.join(save_file.sub(/\.chat\z/, '') + '.society', 'Worker', 'run', 'agent.chat')
119
+ FileUtils.mkdir_p(File.dirname(child))
120
+ Open.write(child, chat_text({role: 'user', content: 'go'},
121
+ {role: 'meta', content: 'job=WF/ask/one'}))
122
+
123
+ report = Chat.live_report(save_file, captured: ['WF/ask/one'])
124
+ assert_equal [], report[:entries]
125
+ end
126
+
127
+ def test_cycle_and_depth_guards_terminate
128
+ a_dir = write_info('WF/a/one', 'running', Process.pid, type: 'chat')
129
+ b_dir = write_info('WF/b/one', 'running', Process.pid, type: 'chat')
130
+ File.write(a_dir + '.info',
131
+ JSON.dump({status: 'running', pid: Process.pid, type: 'chat',
132
+ workflow: 'WF', task_name: 'a',
133
+ dependencies: [b_dir]}))
134
+ File.write(b_dir + '.info',
135
+ JSON.dump({status: 'running', pid: Process.pid, type: 'chat',
136
+ workflow: 'WF', task_name: 'b',
137
+ dependencies: [a_dir]}))
138
+
139
+ expanded = Chat.expand_live_jobs(['WF/a/one'])
140
+ assert_equal 2, expanded.length,
141
+ 'cycle must terminate, visiting each job once'
142
+
143
+ # Depth cap: a 10-link chain expands LIVE_DEPENDENCY_DEPTH_LIMIT + 1
144
+ # nodes (the entry itself plus 5 dependency levels).
145
+ dirs = (0..9).collect do |i|
146
+ write_info("WF/chain_#{i}/one", 'running', Process.pid, type: 'chat')
147
+ end
148
+ dirs.each_cons(2) do |parent, child|
149
+ info = JSON.parse(File.read(parent + '.info'))
150
+ info['dependencies'] = [child]
151
+ File.write(parent + '.info', JSON.dump(info))
152
+ end
153
+
154
+ expanded = Chat.expand_live_jobs(['WF/chain_0/one'])
155
+ assert_equal Chat::LIVE_DEPENDENCY_DEPTH_LIMIT + 1, expanded.length
156
+ end
157
+
158
+ def test_nothing_anywhere_is_silent
159
+ Open.rm_rf save_file
160
+ assert_equal({entries: [], scanned: {sidecar: false, agent_view: false,
161
+ society: false}},
162
+ Chat.live_report(save_file, captured: []))
163
+ end
164
+
165
+ def test_running_non_chat_job_is_workload_context
166
+ write_info('WF/load/one', 'running', Process.pid)
167
+ write_sidecar(['WF/load/one'])
168
+
169
+ report = Chat.live_report(save_file, captured: [])
170
+ assert_equal [:workload_context], report[:entries].collect { |e| e[:kind] }
171
+ assert !report[:entries].first[:chat_task]
172
+ end
173
+
174
+ def test_waiting_wrapper_finds_running_dependency
175
+ # The p4 shape: while the chat_task dependency runs, the WRAPPER's
176
+ # `.info` is still `{"status":"waiting"}` — no pid, no `dependencies`
177
+ # key (scout-gear records them only after run_dependencies returns).
178
+ dep_dir = write_info('WF/continue/one', 'start', Process.pid, type: 'chat')
179
+ wrap_dir = write_info('WF/cortex_continue/one', 'waiting', nil)
180
+ # erase the dependencies key entirely, like init_info's pre-persist state
181
+ File.write(wrap_dir + '.info', JSON.dump({status: 'waiting'}))
182
+ write_agent_log('WF/continue/one', chat_text({role: 'user', content: 'go'}))
183
+ write_sidecar(['WF/cortex_continue/one'])
184
+
185
+ report = Chat.live_report(save_file, captured: [])
186
+ inference = report[:entries].select { |e| e[:kind] == :inference }
187
+ assert_equal 1, inference.length, 'fallback must surface the dependency'
188
+ assert_equal dep_dir, inference.first[:path]
189
+ assert_equal wfdir['WF/continue/one.files/agent.chat'].find.to_s,
190
+ inference.first[:agent_log]
191
+
192
+ # The waiting wrapper itself is reported once, as workload context,
193
+ # state :waiting (not crashed).
194
+ wrappers = report[:entries].select do |e|
195
+ e[:path] == wrap_dir
196
+ end
197
+ assert_equal 1, wrappers.length, 'wrapper appears exactly once'
198
+ assert_equal :workload_context, wrappers.first[:kind]
199
+ assert_equal :waiting, wrappers.first[:state]
200
+ end
201
+
202
+ def test_done_wrapper_uses_recorded_dependencies
203
+ # A DONE-shaped wrapper carries dependencies in `.info`: the normal
204
+ # path must be taken; the fallback must contribute nothing.
205
+ dep_dir = write_info('WF/continue/one', 'start', Process.pid, type: 'chat')
206
+ wrap_dir = write_info('WF/cortex_continue/one', 'waiting', nil,
207
+ deps: [dep_dir])
208
+ write_sidecar(['WF/cortex_continue/one'])
209
+
210
+ expanded = Chat.expand_live_jobs(['WF/cortex_continue/one'])
211
+ assert expanded.any? { |e| e[:path] == dep_dir },
212
+ 'recorded dependencies are still walked'
213
+ assert expanded.none? { |e| e[:state] == :waiting },
214
+ 'recorded path never marks the wrapper waiting'
215
+ end
216
+
217
+ def test_unresolvable_namespace_is_fail_soft
218
+ # A wrapper whose task namespace has no other job directories: the
219
+ # fallback finds nothing and must not raise.
220
+ write_info('WF/solo/one', 'waiting', nil)
221
+ sidecar_only = Chat.jobs_file(save_file)
222
+ Open.rm_rf sidecar_only
223
+ File.write(sidecar_only, "WF/solo/one\n")
224
+
225
+ expanded = Chat.expand_live_jobs(['WF/solo/one'])
226
+ assert_equal [], expanded
227
+
228
+ report = Chat.live_report(save_file, captured: [])
229
+ assert_equal [], report[:entries]
230
+ end
231
+
232
+ def test_dependency_candidates_skip_finished_and_captured
233
+ # Sibling jobs that are finished (done) or crashed (dead pid) are not
234
+ # candidates; only a live sibling is.
235
+ write_info('WF/continue/old', 'done', 999_999_999, type: 'chat')
236
+ dep_dir = write_info('WF/continue/one', 'start', Process.pid, type: 'chat')
237
+ wrap_dir = write_info('WF/cortex_continue/one', 'waiting', nil)
238
+
239
+ cands = Chat.live_dependency_candidates(Step.load(wrap_dir))
240
+ assert_equal [dep_dir], cands.collect { |s| s.path.to_s },
241
+ 'only the running sibling qualifies'
242
+
243
+ # Captured ids still dedup: the dependency already in the main report
244
+ # is dropped everywhere.
245
+ report = Chat.live_report(save_file, captured: ['WF/continue/one'])
246
+ assert_equal [], report[:entries]
247
+ end
248
+
249
+ def test_scanned_flags_reflect_what_was_present
250
+ write_info('WF/ask/one', 'running', Process.pid, type: 'chat')
251
+ write_sidecar(['WF/ask/one'])
252
+ Open.write(save_file, chat_text({role: 'user', content: 'go'}))
253
+
254
+ report = Chat.live_report(save_file, captured: [])
255
+ assert report[:scanned][:sidecar], 'sidecar was present'
256
+ assert report[:scanned][:agent_view], 'agent save file existed'
257
+ assert !report[:scanned][:society], 'no society tree existed'
258
+ end
259
+
260
+ # Round-2 pin (bout 1). The documented fold rule in
261
+ # lib/scout/llm/chat/provenance/live.rb (~447-457): for one agent log
262
+ # carrying BOTH live trailing activity and a dangling `job=` meta that
263
+ # resolves to a running job, the per-log fold yields ONE entry whose
264
+ # kind is :dangling_job (the dangling job wins as the kind) with the
265
+ # activity facts riding along. Pinned BEFORE the round-2 semantic
266
+ # reconciliation so the later change is test-guarded.
267
+ def test_dangling_job_wins_kind_over_agent_activity_for_same_log
268
+ write_info('WF/ask/one', 'running', Process.pid, type: 'chat')
269
+ Open.write(save_file, chat_text({role: 'user', content: 'go'},
270
+ {role: 'meta', content: 'job=WF/ask/one'}))
271
+
272
+ report = Chat.live_report(save_file, captured: [])
273
+ assert_equal 1, report[:entries].length,
274
+ 'one agent log folds to at most one entry'
275
+ entry = report[:entries].first
276
+ assert_equal :dangling_job, entry[:kind],
277
+ 'documented precedence: the dangling job wins as the kind'
278
+ assert_equal 'WF/ask/one', entry[:reference]
279
+ assert entry[:activity] || entry[:reason],
280
+ 'activity facts ride along with the dangling job entry'
281
+ end
282
+ end