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
@@ -35,7 +35,7 @@ class TestChatAgentMetaProvenance < Test::Unit::TestCase
35
35
 
36
36
  # The worker log chat is reached through the ordinary :log relation and
37
37
  # the worker dependency through :dependency.
38
- worker_log = File.join(worker + '.files', 'log', 'agent.chat')
38
+ worker_log = File.join(worker + '.files', 'agent.chat')
39
39
  assert signature.any? { |kind, path, relation, _first| kind == :chat && path == worker_log && relation == :log }
40
40
  assert signature.any? { |_kind, path, relation, _first| relation == :dependency && path.end_with?('Dep/load/Default_1') }
41
41
 
@@ -45,6 +45,77 @@ class TestChatAgentMetaProvenance < Test::Unit::TestCase
45
45
  end
46
46
  end
47
47
 
48
+ ## Envelope variants (current `meta` key) and repeated references ##
49
+
50
+ # The current envelope writes receipts under the `meta` key of the
51
+ # function_call_output payload instead of the legacy `agent_meta` array.
52
+ # Both must yield :agent_job edges from the enclosing chat.
53
+ def test_current_meta_envelope_receipt_yields_agent_job_edge
54
+ TmpFile.with_dir do |dir|
55
+ child = make_job(dir, 'Cortex/continue/Default_cur.chat')
56
+ parent = write_chat(dir, 'parent.chat',
57
+ receipt_chat_text({'a1' => [{'job' => child}]},
58
+ envelope: :meta))
59
+
60
+ errors = []
61
+ visits = Chat.traverse_provenance(parent, on_error: ->(*args) { errors << args }).to_a
62
+
63
+ assert_empty errors
64
+ signature = visit_signature(visits)
65
+ edge = signature.find { |_kind, path, relation, _first| relation == :agent_job && path == child }
66
+ assert edge, "no :agent_job edge to #{child} in #{signature.inspect}"
67
+ assert_equal :job, edge[0]
68
+ end
69
+ end
70
+
71
+ # Job references recorded by chat_task point at the .chat result file
72
+ # (e.g. Cortex/continue/Default_x.chat); resolution must work for them too.
73
+ def test_chat_typed_job_reference_resolves
74
+ TmpFile.with_dir do |dir|
75
+ child = make_job(dir, 'Cortex/continue/Default_x.chat')
76
+ parent = write_chat(dir, 'parent.chat',
77
+ receipt_chat_text({'a1' => [{'job' => child}]},
78
+ envelope: :meta))
79
+
80
+ errors = []
81
+ visits = Chat.traverse_provenance(parent, on_error: ->(*args) { errors << args }).to_a
82
+
83
+ assert_empty errors
84
+ signature = visit_signature(visits)
85
+ assert signature.any? { |_kind, path, relation, _first| relation == :agent_job && path == child },
86
+ signature.inspect
87
+ end
88
+ end
89
+
90
+ # Several continuations of one conversation report the SAME child job ref
91
+ # from one parent (the user-visible case: three Cortex/continue calls).
92
+ # Each receipt keeps its own edge and detail, the child node expands once.
93
+ def test_repeated_job_references_keep_distinct_edges_and_expand_once
94
+ TmpFile.with_dir do |dir|
95
+ child = make_job(dir, 'Cortex/continue/Default_dup.chat')
96
+ receipt = [{'job' => child}]
97
+ parent = write_chat(dir, 'parent.chat',
98
+ receipt_chat_text({'a1' => receipt, 'a2' => receipt, 'a3' => receipt},
99
+ envelope: :meta))
100
+
101
+ errors = []
102
+ visits = Chat.traverse_provenance(parent, on_error: ->(*args) { errors << args }).to_a
103
+
104
+ assert_empty errors
105
+ delegated = visits.select { |v| v[4] == :agent_job }
106
+ assert_equal 3, delegated.length, 'each receipt keeps its own edge'
107
+ delegated.each_with_index do |visit, i|
108
+ assert_equal child, visit[1].path.to_s
109
+ assert_equal "a#{i + 1}", visit[6][:call_id], 'edge detail keeps the originating call id'
110
+ end
111
+ assert_equal [true, false, false], delegated.collect { |v| v[5] },
112
+ 'only the first visit expands the child node'
113
+ # Three edges to the SAME job node are structural: only the first one
114
+ # expands it (visit count 3, single expansion flag set).
115
+ assert_equal 3, visits.count { |kind, object, *_| kind == :job && object.path.to_s == child }
116
+ end
117
+ end
118
+
48
119
  def test_follow_job_excludes_the_agent_job_edge
49
120
  TmpFile.with_dir do |dir|
50
121
  parent, _worker, _critic, _dep = fixture_c(dir)
@@ -112,7 +183,7 @@ class TestChatAgentMetaProvenance < Test::Unit::TestCase
112
183
  assert delegated.any? { |_kind, path, _first| path == worker }
113
184
  assert delegated.any? { |_kind, path, _first| path == critic }
114
185
 
115
- worker_log = File.join(worker + '.files', 'log', 'agent.chat')
186
+ worker_log = File.join(worker + '.files', 'agent.chat')
116
187
  nested = visits.find do |kind, object, _pk, p, rel, _first|
117
188
  kind == :job && object.path.to_s == critic && rel == :agent_job && p.to_s == worker_log
118
189
  end
@@ -164,19 +235,18 @@ class TestChatAgentMetaProvenance < Test::Unit::TestCase
164
235
  chat = write_chat(dir, 'bad.chat',
165
236
  receipt_chat_text(
166
237
  {'b1' => 'not-an-array',
167
- 'b2' => [{role: 'assistant', content: 'pt=1 tt=2'},
168
- meta_receipt('no parseable pairs at all')],
169
- 'b3' => [meta_receipt('also not parseable')]}
238
+ 'b2' => ['plain-string-entry', Chat.parse_meta('pt=1 tt=2')],
239
+ 'b3' => [{}]}
170
240
  ))
171
241
 
172
242
  errors = []
173
243
  visits = Chat.traverse_provenance(chat, on_error: ->(*args) { errors << args }).to_a
174
244
 
175
- assert_equal 4, errors.length
245
+ assert_equal 3, errors.length
176
246
  reasons = errors.collect { |_error, _kind, _object, _relation, reference| reference[:reason] }
177
247
  assert_include reasons, :not_an_array
178
- assert_include reasons, :invalid_role
179
- assert_equal 2, reasons.count(:unparseable_meta)
248
+ assert_include reasons, :not_a_hash
249
+ assert_include reasons, :empty_meta
180
250
 
181
251
  errors.each do |error, kind, object, relation, reference|
182
252
  assert_kind_of ScoutException, error
@@ -200,11 +270,11 @@ class TestChatAgentMetaProvenance < Test::Unit::TestCase
200
270
  assert_equal [chat, 2], not_an_array.last[:output_address]
201
271
  assert_nil not_an_array.last[:evidence_address]
202
272
  assert_nil not_an_array.last[:agent_meta_index]
203
- invalid_role = errors.find { |_e, _k, _o, _r, ref| ref[:reason] == :invalid_role }
204
- assert_equal [chat, 4, :agent_meta, 0], invalid_role.last[:evidence_address]
205
- assert_equal 0, invalid_role.last[:agent_meta_index]
206
- unparseable = errors.find { |_e, _k, _o, _r, ref| ref[:reason] == :unparseable_meta && ref[:output_address] == [chat, 4] }
207
- assert_equal [chat, 4, :agent_meta, 1], unparseable.last[:evidence_address]
273
+ not_a_hash = errors.find { |_e, _k, _o, _r, ref| ref[:reason] == :not_a_hash }
274
+ assert_equal [chat, 4, :meta, 0], not_a_hash.last[:evidence_address]
275
+ assert_equal 0, not_a_hash.last[:agent_meta_index]
276
+ empty_meta = errors.find { |_e, _k, _o, _r, ref| ref[:reason] == :empty_meta }
277
+ assert_equal [chat, 6, :meta, 0], empty_meta.last[:evidence_address]
208
278
 
209
279
  # Nothing malformed was silently used as provenance.
210
280
  assert_equal 1, visits.length
@@ -264,7 +334,7 @@ TXT
264
334
  unresolved = errors.collect(&:last).select { |ref| ref[:reason] == :unresolved_job_reference }
265
335
  assert_equal 1, unresolved.length
266
336
  assert_equal missing, unresolved.first[:reference]
267
- assert_equal [chat, 2, :agent_meta, 0], unresolved.first[:evidence_address]
337
+ assert_equal [chat, 2, :meta, 0], unresolved.first[:evidence_address]
268
338
  assert_equal 'u1', unresolved.first[:call_id]
269
339
  assert_equal 'ask', unresolved.first[:tool_name]
270
340
 
@@ -320,12 +390,12 @@ TXT
320
390
  def test_strict_mode_raises_on_malformed_receipt
321
391
  TmpFile.with_dir do |dir|
322
392
  chat = write_chat(dir, 'strict-bad.chat',
323
- receipt_chat_text({'s1' => [{role: 'assistant', content: 'x'}]}))
393
+ receipt_chat_text({'s1' => ['not-a-hash-entry']}))
324
394
 
325
395
  error = assert_raise(ScoutException) do
326
396
  Chat.traverse_provenance(chat).to_a
327
397
  end
328
- assert_match(/invalid_role/, error.message)
398
+ assert_match(/not_a_hash/, error.message)
329
399
  end
330
400
  end
331
401
 
@@ -348,7 +418,7 @@ TXT
348
418
  chat = write_chat(dir, 'saved.chat',
349
419
  "user: hi\nmeta: pt=2 ct=1 tt=3 inference_id=s0\nassistant: done\n")
350
420
 
351
- sidecar = File.expand_path(chat + '.files/log/society/Worker/default')
421
+ sidecar = File.expand_path(chat + '.files/agent.society/Worker/default')
352
422
  FileUtils.mkdir_p(sidecar)
353
423
  File.write(File.join(sidecar, 'agent.chat'),
354
424
  "user: work\nmeta: pt=10 ct=5 tt=15 inference_id=w1\nassistant: ok\n")
@@ -359,7 +429,7 @@ TXT
359
429
  assert_empty errors
360
430
 
361
431
  society = visits.find do |_kind, object, _pk, _parent, _relation, _first|
362
- object.to_s.end_with?('log/society/Worker/default/agent.chat')
432
+ object.to_s.end_with?('agent.society/Worker/default/agent.chat')
363
433
  end
364
434
  assert society, 'society chat not visited'
365
435
  kind, object, parent_kind, parent, relation, first = society
@@ -377,12 +447,12 @@ TXT
377
447
  chat = write_chat(dir, 'saved.chat',
378
448
  "user: hi\nmeta: pt=2 ct=1 tt=3 inference_id=s0\nassistant: done\n")
379
449
 
380
- log = File.expand_path(chat + '.files/log')
381
- FileUtils.mkdir_p(File.join(log, 'society/Worker/default'))
450
+ log = File.expand_path(chat + '.files')
451
+ FileUtils.mkdir_p(File.join(log, 'agent.society/Worker/default'))
382
452
  # The full-copy written by the CLI save mechanism: same content as root.
383
453
  File.write(File.join(log, 'agent.chat'),
384
454
  "user: hi\nmeta: pt=2 ct=1 tt=3 inference_id=s0\nassistant: done\n")
385
- File.write(File.join(log, 'society/Worker/default/agent.chat'),
455
+ File.write(File.join(log, 'agent.society/Worker/default/agent.chat'),
386
456
  "user: work\nmeta: pt=10 ct=5 tt=15 inference_id=w1\nassistant: ok\n")
387
457
 
388
458
  visits = Chat.traverse_provenance(chat).to_a
@@ -391,7 +461,7 @@ TXT
391
461
  root_copy = File.join(log, 'agent.chat')
392
462
  assert_not_include paths, root_copy,
393
463
  'the sidecar root copy must not become its own node'
394
- assert_include paths, File.join(log, 'society/Worker/default/agent.chat')
464
+ assert_include paths, File.join(log, 'agent.society/Worker/default/agent.chat')
395
465
 
396
466
  # No chat -> root-copy edge either.
397
467
  edges = Chat.provenance_edges(chat).collect { |e| [e[:from].to_s, e[:to].to_s, e[:relation]] }
@@ -399,19 +469,59 @@ TXT
399
469
  end
400
470
  end
401
471
 
472
+ # The Lean regression at the agent-meta level: the top-level sidecar is the
473
+ # agent TRANSCRIPT (not a copy of the root conversation) and it is the only
474
+ # place the session's meta job= references live. A chat-root traversal must
475
+ # follow them into the job tree.
476
+ def test_saved_chat_follows_job_refs_in_its_transcript_sidecar
477
+ TmpFile.with_dir do |dir|
478
+ worker = make_job(dir, 'Planned/work/Default_1',
479
+ logs: {'agent.chat' =>
480
+ "user: work\nmeta: pt=10 ct=5 tt=15 inference_id=w1\nassistant: ok\n"})
481
+ chat = write_chat(dir, 'saved.chat',
482
+ "user: hi\nmeta: pt=2 ct=1 tt=3 inference_id=s0\nassistant: done\n")
483
+
484
+ log = File.expand_path(chat + '.files')
485
+ FileUtils.mkdir_p(log)
486
+ # Transcript: carries the delegated job receipt the root file lacks.
487
+ File.write(File.join(log, 'agent.chat'),
488
+ "system: you are the harness\n" \
489
+ "user: hi\nmeta: pt=2 ct=1 tt=3 inference_id=s0\nassistant: done\n" \
490
+ "user: go\nmeta: job=#{worker}\nassistant: done\n")
491
+
492
+ visits = Chat.traverse_provenance(chat).to_a
493
+ paths = visits.collect { |_k, object, _pk, _p, _r, _f| object.to_s }
494
+ job_paths = visits.select { |kind, *_| kind == :job }
495
+ .collect { |_k, object, *_| object.path.to_s }
496
+
497
+ transcript = File.join(log, 'agent.chat')
498
+ assert_include paths, transcript,
499
+ 'the transcript sidecar must be visited from the chat root'
500
+ assert_include job_paths, worker,
501
+ 'the job referenced only by the transcript must be reached'
502
+ assert_include paths, File.join(worker.to_s + '.files', 'agent.chat'),
503
+ 'the referenced job log chat must be reached'
504
+
505
+ # Identity grouping keeps s0 counted once even though the transcript
506
+ # repeats the root conversation before adding its own turns.
507
+ assert_equal({pt: 12, ct: 6, tt: 18, cct: 0, cwt: 0, rt: 0},
508
+ Chat.provenance_token_totals(chat))
509
+ end
510
+ end
511
+
402
512
  def test_saved_chat_sidecar_visits_are_unique_and_repeateable
403
513
  TmpFile.with_dir do |dir|
404
514
  chat = write_chat(dir, 'saved.chat',
405
515
  "user: hi\nmeta: pt=2 ct=1 tt=3 inference_id=s0\nassistant: done\n")
406
516
 
407
- log = File.expand_path(chat + '.files/log')
408
- FileUtils.mkdir_p(File.join(log, 'society/Worker/default'))
409
- FileUtils.mkdir_p(File.join(log, 'society/Critic/default'))
517
+ log = File.expand_path(chat + '.files')
518
+ FileUtils.mkdir_p(File.join(log, 'agent.society/Worker/default'))
519
+ FileUtils.mkdir_p(File.join(log, 'agent.society/Critic/default'))
410
520
  File.write(File.join(log, 'agent.chat'),
411
521
  "user: hi\nmeta: pt=2 ct=1 tt=3 inference_id=s0\nassistant: done\n")
412
- File.write(File.join(log, 'society/Worker/default/agent.chat'),
522
+ File.write(File.join(log, 'agent.society/Worker/default/agent.chat'),
413
523
  "user: work\nmeta: pt=10 ct=5 tt=15 inference_id=w1\nassistant: ok\n")
414
- File.write(File.join(log, 'society/Critic/default/agent.chat'),
524
+ File.write(File.join(log, 'agent.society/Critic/default/agent.chat'),
415
525
  "user: check\nmeta: pt=4 ct=2 tt=6 inference_id=c1\nassistant: fine\n")
416
526
 
417
527
  keys = nil
@@ -430,7 +540,7 @@ TXT
430
540
  TmpFile.with_dir do |dir|
431
541
  _parent, worker, _critic, _dep = fixture_c(dir)
432
542
 
433
- log = Path.setup(File.expand_path(File.join(worker.to_s + '.files', 'log')))
543
+ log = Path.setup(File.expand_path(File.join(worker.to_s + '.files')))
434
544
  log_chat = File.join(log.to_s, 'agent.chat')
435
545
  assert File.file?(log_chat), 'fixture did not create the job log chat'
436
546
 
@@ -448,6 +558,68 @@ TXT
448
558
 
449
559
  ## Regression
450
560
 
561
+ ## Reviewer pins: no tool-name gating on the :agent_job edge
562
+
563
+ # The edge exists for ANY tool whose function_call_output envelope carries a
564
+ # meta[].job receipt; the function name is irrelevant to accounting. Proven
565
+ # by fabricating a tool name that is not a scout-ai task (`not_ask`) and by
566
+ # reusing the names of the receipt-producing workflows (`cortex_continue`,
567
+ # `cortex_brief`) on a non-delegating envelope as a negative control.
568
+ def test_agent_job_edge_under_arbitrary_tool_names
569
+ TmpFile.with_dir do |dir|
570
+ child = make_job(dir, 'Cortex/continue/Default_tn.chat')
571
+
572
+ %w[not_ask cortex_continue cortex_brief].each do |tool|
573
+ parent = write_chat(dir, "parent_#{tool}.chat",
574
+ receipt_chat_text({'a1' => [{'job' => child}]},
575
+ envelope: :meta, tool: tool))
576
+ signature = visit_signature(Chat.traverse_provenance(parent).to_a)
577
+ assert signature.any? { |_kind, path, relation, _first|
578
+ relation == :agent_job && path == child
579
+ }, "no :agent_job edge for tool #{tool}: #{signature.inspect}"
580
+ end
581
+
582
+ # Negative control: same tool names, envelope without a job receipt ->
583
+ # no edge, so the edge follows the receipt, not the name.
584
+ %w[not_ask cortex_continue cortex_brief].each do |tool|
585
+ parent = write_chat(dir, "plain_#{tool}.chat",
586
+ receipt_chat_text({'a1' => [{'role' => 'meta',
587
+ 'content' => 'ok'}]},
588
+ envelope: :meta, tool: tool))
589
+ signature = visit_signature(Chat.traverse_provenance(parent).to_a)
590
+ assert_empty signature.select { |_kind, _path, relation, _first| relation == :agent_job },
591
+ "unexpected :agent_job edge for tool #{tool}"
592
+ end
593
+ end
594
+ end
595
+
596
+ # Structural double check: the provenance source contains no conditional on
597
+ # a function/tool name anywhere in the receipt lifting path. The check
598
+ # looks for gating CONSTRUCTS around the tool name (==/match/case), not for
599
+ # the bare word, because `tool_name` is legitimately recorded as evidence
600
+ # detail.
601
+ def test_no_tool_name_conditional_in_provenance_sources
602
+ source = File.read(File.expand_path('../../../../lib/scout/llm/chat/provenance.rb', __dir__))
603
+ # 1. no equality/matching test between the name and a literal tool name
604
+ %w[ask cortex_continue cortex_brief not_ask].each do |name|
605
+ ["tool_name == :#{name}",
606
+ "tool_name.to_s == '#{name}'",
607
+ "tool_name == '#{name}'",
608
+ "name == '#{name}'",
609
+ "tool_name =~ /#{name}/",
610
+ "'name' => '#{name}'"].each do |pattern|
611
+ assert_not_include source, pattern,
612
+ "tool-name conditional #{pattern.inspect} leaked into provenance traversal"
613
+ end
614
+ end
615
+ # 2. no case/when branch on the name at all
616
+ assert_not_match(/^\s*case\s+(\S*tool_name|name)\s*$/, source)
617
+ # 3. the word only appears as evidence detail, never as a value compared
618
+ # (the literal name recorded by callers lives in test fixtures, not here)
619
+ assert_not_include source, "tool_name =='", source
620
+ assert_not_include source, 'tool_name==', source
621
+ end
622
+
451
623
  def test_provenance_relations_include_agent_job_and_not_import
452
624
  assert_equal %i[job dependency log result agent_job], Chat::PROVENANCE_RELATIONS
453
625
  assert_not_include Chat::PROVENANCE_RELATIONS, :import
@@ -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 }
@@ -511,6 +511,60 @@ class TestChatAgentMetaTokens < Test::Unit::TestCase
511
511
  end
512
512
  end
513
513
 
514
+ # Continuation chain: a job's accounting delta is its RESULT CHAT ONLY, even
515
+ # though its persisted agent log also carries the whole projected parent
516
+ # history. The synthetic A/B/C chain from the review (theme 2) is rebuilt
517
+ # here in miniature; the history stays inspectable through the ordinary
518
+ # :log relation, so nothing is truncated, it just is not counted twice.
519
+ def test_continuation_chain_delta_is_result_chat_only
520
+ TmpFile.with_dir do |dir|
521
+ a_meta = (1..3).collect { |i| "meta: pt=10 tt=10 inference_id=a#{i}" }
522
+ b_meta = (1..2).collect { |i| "meta: pt=100 tt=100 inference_id=b#{i}" }
523
+
524
+ # Job A: fresh conversation; result chat = 3 metas; log = same 3.
525
+ make_job(dir, 'Chain/continue/Default_A', result: "user: a\n#{a_meta * "\n"}\n",
526
+ logs: {'agent.chat' => "user: a\n#{a_meta * "\n"}\n"})
527
+
528
+ # Job B: continuation of A; result chat = B's own 2 metas; log = the
529
+ # cumulative agent history (A's 3 projected + B's 2).
530
+ b_log = ["user: a\n", a_meta, "user: b\n", b_meta].flatten.join("\n")
531
+ b_result = "user: b\n#{b_meta * "\n"}\n"
532
+ b = make_job(dir, 'Chain/continue/Default_B', result: b_result,
533
+ logs: {'agent.chat' => b_log})
534
+
535
+ # Type the job result as chat so Chat.job_result_chat_file resolves it.
536
+ info = JSON.parse(File.read(b + '.info'))
537
+ File.write(b + '.info', {dependencies: info['dependencies'], type: :chat}.to_json)
538
+
539
+ result_chat = Chat.job_result_chat_file(Step.load(b))
540
+ assert result_chat, 'B has a chat-typed persisted result'
541
+ assert_equal({pt: 200, ct: 0, tt: 200, cct: 0, cwt: 0, rt: 0},
542
+ Chat.token_totals([Chat.load(result_chat)]),
543
+ 'B delta = its own new metas only, not the projected history')
544
+
545
+ # The cumulative log remains fully inspectable: its direct totals still
546
+ # count 3 + 2 events (30 + 200 = 230), and the traversal still reaches
547
+ # it through the ordinary :log relation.
548
+ log_path = File.join(b + '.files', 'agent.chat')
549
+ assert_equal({pt: 230, ct: 0, tt: 230, cct: 0, cwt: 0, rt: 0},
550
+ Chat.token_totals([Chat.load(log_path)]),
551
+ 'the history itself is untouched and readable')
552
+ # Traversed from the JOB root (the accounting root of a chat_task run);
553
+ # a bare path string would be interpreted as a chat root, so load the
554
+ # Step. The cumulative log is visited through the ordinary :log relation.
555
+ visits = Chat.traverse_provenance(Step.load(b)).to_a
556
+ assert visits.any? { |k, o, _pk, _p, r, _f| k == :chat && o.to_s == log_path && r == :log },
557
+ 'cumulative log is traversed, not dropped'
558
+
559
+ # Whole-chain accounting from the B root keeps one copy of each event:
560
+ # 3 A metas (30) + 2 B metas (200) = 230, not the sum of the two files
561
+ # (130 + 130) and not B's delta alone (200).
562
+ assert_equal({pt: 230, ct: 0, tt: 230, cct: 0, cwt: 0, rt: 0},
563
+ Chat.provenance_token_totals(Step.load(b)),
564
+ 'deduplicated chain total = A metas + B metas, once each')
565
+ end
566
+ end
567
+
514
568
  # Two separate ask receipts pointing at the same job= keep both edge details
515
569
  # (distinct call ids and receipt addresses) while the Step is visited once.
516
570
  def test_two_receipts_to_the_same_job_keep_both_edge_details
@@ -582,6 +636,57 @@ class TestChatAgentMetaTokens < Test::Unit::TestCase
582
636
 
583
637
  ## Scope validation
584
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
+
585
690
  def test_unknown_scope_raises
586
691
  TmpFile.with_dir do |dir|
587
692
  path = write_chat(dir, 'any.chat', "user: hi\nassistant: done\n")