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
@@ -68,10 +68,14 @@ class TestProvCLI < Test::Unit::TestCase
68
68
  out, _err, status = prov(parent)
69
69
  assert status.success?
70
70
 
71
- # Cross-consumer equality: the root chat line carries the collector total.
71
+ # Cross-consumer equality: the root chat line carries the collector total
72
+ # under the evidence= label (subtree-deduplicated closure).
72
73
  root_line = out.lines.find { |line| line.include?('parent.chat') }
73
74
  assert root_line, out
74
- assert root_line.include?("total=#{expected[:tt]}"), root_line
75
+ assert root_line.include?("evidence=#{expected[:tt]}"), root_line
76
+
77
+ # The authoritative root footer always follows the tree.
78
+ assert_match(/root deduplicated_total=#{expected[:tt]} /, out)
75
79
 
76
80
  # One delegated annotation line for the two receipt events (w1 + w2).
77
81
  assert_match(/delegated receipt: 2 events, total=180/, out)
@@ -88,7 +92,7 @@ class TestProvCLI < Test::Unit::TestCase
88
92
  # must be rendered as a chat root, never loaded as a Step.
89
93
  saved = write_chat(dir, 'saved.chat',
90
94
  "user: hi\nmeta: pt=1 ct=1 tt=2 inference_id=s1\nassistant: done\n")
91
- society_chat = File.join(saved + '.files', 'log', 'society', 'Worker', 'default', 'agent.chat')
95
+ society_chat = File.join(saved + '.files', 'agent.society', 'Worker', 'default', 'agent.chat')
92
96
  FileUtils.mkdir_p(File.dirname(society_chat))
93
97
  File.write(society_chat,
94
98
  "user: work\nmeta: pt=5 ct=2 tt=7 inference_id=s2\nassistant: ok\n")
@@ -105,14 +109,16 @@ class TestProvCLI < Test::Unit::TestCase
105
109
  assert root_line, out
106
110
  assert_match(/\A\s*chat\b/, root_line, out)
107
111
  assert_not_match(/\A\s*job\b/, root_line, out)
108
- assert_include root_line, 'total=9', out
112
+ assert_include root_line, 'evidence=9', out
109
113
  assert_include root_line, 'prompt=6', out
114
+ assert_match(/root deduplicated_total=9 /, out)
110
115
 
111
- # The society conversation is traversed and rendered as its own node.
112
- society_line = out.lines.find { |line| line.include?('log/society/Worker/default/agent.chat') }
116
+ # The society conversation is traversed and rendered as its own node,
117
+ # labeled with its agent/conversation pair in the short form.
118
+ society_line = out.lines.find { |line| line.include?('society Worker/default') }
113
119
  assert society_line, out
114
120
  assert_match(/\A\s*chat\b/, society_line, out)
115
- assert_include society_line, 'total=7', out
121
+ assert_include society_line, 'evidence=7', out
116
122
  assert_include society_line, 'prompt=5', out
117
123
  end
118
124
  end
@@ -132,8 +138,8 @@ class TestProvCLI < Test::Unit::TestCase
132
138
  end
133
139
 
134
140
  # Receipt evidence keeps its parent output address and call id.
135
- assert_match(/agent_meta parent\.chat:2\[agent_meta,0\] call=a1/, out)
136
- assert_match(/agent_meta parent\.chat:2\[agent_meta,1\] call=a1/, out)
141
+ assert_match(/agent_meta parent\.chat:2\[meta,0\] call=a1/, out)
142
+ assert_match(/agent_meta parent\.chat:2\[meta,1\] call=a1/, out)
137
143
 
138
144
  # Chat-side evidence for the merged events.
139
145
  assert_match(/chat_meta agent\.chat:3/, out)
@@ -195,13 +201,15 @@ class TestProvCLI < Test::Unit::TestCase
195
201
 
196
202
  out, _err, status = prov('--component', parent)
197
203
  assert status.success?
198
- assert_include out, 'evidence deduplicated_total:'
199
204
  assert_include out, 'evidence chat_evidence:'
200
205
  assert_include out, 'evidence receipt_evidence:'
201
206
  assert_include out, 'evidence receipt_only:'
202
207
 
203
208
  expected = Chat.provenance_token_totals(parent)
204
- assert_match(/evidence deduplicated_total: total=#{expected[:tt]}/, out)
209
+ # The scope block no longer repeats the authoritative total; the root
210
+ # footer (printed in both modes) is its single home.
211
+ assert_not_include out, 'evidence deduplicated_total:', 'scope block must stay 3 lines'
212
+ assert_match(/root deduplicated_total=#{expected[:tt]} /, out)
205
213
 
206
214
  # Coverage figures are explicitly labelled as overlapping; nothing in
207
215
  # the output invites summing them.
@@ -210,6 +218,8 @@ class TestProvCLI < Test::Unit::TestCase
210
218
 
211
219
  # No conflicts in this fixture: no non-authoritative label.
212
220
  assert_not_include out, 'not exact', out
221
+ # The -c conflict caveat comes from the footer only (still none here).
222
+ assert_not_include out, 'unresolved identity conflicts', out
213
223
  end
214
224
 
215
225
  TmpFile.with_dir do |dir|
@@ -218,6 +228,9 @@ class TestProvCLI < Test::Unit::TestCase
218
228
 
219
229
  out, _err, status = prov('--component', plain)
220
230
  assert status.success?
231
+ # Footer is present in -c even without any receipt evidence.
232
+ assert_match(/root deduplicated_total=2 /, out)
233
+ assert_include out, 'fresh=', out
221
234
  assert_not_include out, 'evidence deduplicated_total:', 'legacy chat must not gain scope lines'
222
235
  assert_not_include out, 'evidence chat_evidence:'
223
236
  assert_not_include out, 'evidence receipt_evidence:'
@@ -228,7 +241,7 @@ class TestProvCLI < Test::Unit::TestCase
228
241
 
229
242
  def test_malformed_receipt_renders_with_warning
230
243
  TmpFile.with_dir do |dir|
231
- payload = {'id' => 'bad1', 'result' => 'x', 'agent_meta' => 'oops'}
244
+ payload = {'id' => 'bad1', 'result' => 'x', 'meta' => 'oops'}
232
245
  text = "user: hi\n" +
233
246
  'function_call: ' + %({"name":"ask","arguments":{},"id":"bad1"}) + "\n" +
234
247
  'function_call_output: ' + JSON.generate(payload) + "\n" +
@@ -266,9 +279,691 @@ class TestProvCLI < Test::Unit::TestCase
266
279
  assert status.success?
267
280
  # Legacy receipt events show their receipt location instead of the raw
268
281
  # address array, and they are flagged as possibly overcounted.
269
- assert_match(/receipt=legacy\.chat:2\[agent_meta,0\]/, out)
282
+ assert_match(/receipt=legacy\.chat:2\[meta,0\]/, out)
270
283
  assert_include out, 'legacy unresolved'
271
284
  assert_not_include out, 'receipt=["', out
272
285
  end
273
286
  end
287
+
288
+ # Option B display contract: job nodes carry delta= (direct tokens of the
289
+ # persisted chat-typed result) alongside evidence=, jobs without a
290
+ # chat-typed result omit the field, and the root footer always follows.
291
+ def test_job_node_delta_labelled_and_footer_present
292
+ TmpFile.with_dir do |dir|
293
+ parent_metas = (1..3).collect { |i| "meta: pt=10 tt=10 inference_id=p#{i}" }
294
+ own_metas = (1..2).collect { |i| "meta: pt=100 tt=100 inference_id=o#{i}" }
295
+ result = "user: b\n#{own_metas * "\n"}\n"
296
+ # The job log is the cumulative history: parent's 3 projected + own 2.
297
+ log = ["user: a", parent_metas, "user: b", own_metas].flatten.join("\n") + "\n"
298
+ job = make_job(dir, 'Chain/continue/Default_d', result: result, logs: {'agent.chat' => log})
299
+ info = JSON.parse(File.read(job + '.info'))
300
+ File.write(job + '.info', {dependencies: info['dependencies'], type: :chat}.to_json)
301
+
302
+ out, _err, status = prov(job)
303
+ assert status.success?
304
+
305
+ # Job line: evidence closure (5 events once = 230) plus delta (200).
306
+ root_line = out.lines.find { |line| line =~ /\A job\b/ }
307
+ assert root_line, out
308
+ assert_include root_line, 'evidence=230', root_line
309
+ assert_include root_line, 'delta=200', root_line
310
+
311
+ # Footer: the authoritative figure, always printed, carrying the event
312
+ # count that no longer lives on the node line.
313
+ assert_match(/root deduplicated_total=230 \(5 events\)/, out)
314
+
315
+ # A job whose result is NOT chat-typed omits delta= entirely.
316
+ plain = make_job(dir, 'Chain/ask/Default_n', result: "answer\n",
317
+ logs: {'agent.chat' => "user: x\nmeta: pt=1 tt=1 inference_id=n1\n"})
318
+ out2, _err2, status2 = prov(plain)
319
+ assert status2.success?
320
+ job_line = out2.lines.find { |line| line =~ /\A job\b/ }
321
+ assert job_line, out2
322
+ assert_include job_line, 'evidence=1', job_line
323
+ assert_not_include job_line, 'delta=', job_line
324
+ assert_match(/root deduplicated_total=1 /, out2)
325
+ end
326
+ end
327
+
328
+ # A JOB root whose top-level agent.chat log carries meta job pointers: the
329
+ # delegated children must appear in the tree nested under the owning job,
330
+ # even though the carrier chat itself stays hidden.
331
+ def test_job_root_delegated_children_nest_in_tree
332
+ TmpFile.with_dir do |dir|
333
+ child1 = make_job(dir, 'Cortex/continue/Default_c1')
334
+ child2 = make_job(dir, 'Cortex/continue/Default_c2')
335
+ worker_log = receipt_chat_text(
336
+ {'w1' => [meta_receipt("job=#{child1}"),
337
+ meta_receipt("job=#{child2}")]}
338
+ )
339
+ worker = make_job(dir, 'Planned/work/Default_w',
340
+ logs: {'agent.chat' => worker_log})
341
+
342
+ out, err, status = prov(worker)
343
+ assert status.success?, err
344
+
345
+ root_line = out.lines.find { |line| line.include?('Default_w') && !line.include?('Default_c') }
346
+ assert root_line, out
347
+ assert_match(/\A job\b/, root_line, out)
348
+
349
+ child_lines = out.lines.select { |line| line =~ /delegated-job .*Default_c[12]/ }
350
+ assert_equal 2, child_lines.length, out
351
+ child_lines.each do |line|
352
+ assert_match(/\A job delegated-job\b/, line, "#{line} must nest two spaces under the job root")
353
+ end
354
+ assert_not_include out, 'agent.chat', 'carrier chat must stay hidden in tree mode'
355
+ end
356
+ end
357
+
358
+ # Deliberate breakage (plan B2): the legacy `agent_meta` envelope key is no
359
+ # longer read. A worker log whose job= receipts travel under the legacy key
360
+ # produces NO delegated children (old chats intentionally lose those edges).
361
+ def test_job_root_legacy_agent_meta_receipt_has_no_children
362
+ TmpFile.with_dir do |dir|
363
+ child = make_job(dir, 'Worker/ask/Default_legacy')
364
+ worker_log = receipt_chat_text(
365
+ {'l1' => [{role: 'meta', content: "job=#{child}"}]},
366
+ envelope: :agent_meta
367
+ )
368
+ worker = make_job(dir, 'Planned/work/Default_wl',
369
+ logs: {'agent.chat' => worker_log})
370
+
371
+ out, _err, status = prov(worker)
372
+ assert status.success?
373
+ assert_not_include out, 'Default_legacy', out
374
+ assert_not_include out, 'delegated-job', out
375
+
376
+ # The same receipt under the current `meta` key DOES produce the child.
377
+ current = receipt_chat_text(
378
+ {'l1' => [{'job' => child}]}
379
+ )
380
+ worker2 = make_job(dir, 'Planned/work/Default_wc',
381
+ logs: {'agent.chat' => current})
382
+ out2, _err, status2 = prov(worker2)
383
+ assert status2.success?
384
+ assert_match(/delegated-job .*Default_legacy/, out2)
385
+ end
386
+ end
387
+
388
+
389
+ # Job refs recorded by chat_task are chat-typed (Cortex/continue/Default_x.chat).
390
+ # Tree mode must resolve them and nest the delegated child once per distinct
391
+ # job, even when the parent repeated the same conversation three times.
392
+ def test_job_root_repeated_meta_refs_nest_once
393
+ TmpFile.with_dir do |dir|
394
+ child = make_job(dir, 'Cortex/continue/Default_dup.chat')
395
+ worker_log = receipt_chat_text(
396
+ {'a1' => [{'job' => child}], 'a2' => [{'job' => child}], 'a3' => [{'job' => child}]},
397
+ envelope: :meta
398
+ )
399
+ worker = make_job(dir, 'Planned/work/Default_w3',
400
+ logs: {'agent.chat' => worker_log})
401
+
402
+ out, err, status = prov(worker)
403
+ assert status.success?, err
404
+
405
+ child_lines = out.lines.select { |line| line =~ /delegated-job .*Default_dup/ }
406
+ assert_equal 1, child_lines.length, out
407
+ assert_match(/\A job delegated-job\b/, child_lines.first, out)
408
+ end
409
+ end
410
+
411
+ # A meta job pointer that does not resolve on disk must degrade to a
412
+ # warning, not an exception, and must not break the tree.
413
+ def test_dangling_meta_job_pointer_warns
414
+ TmpFile.with_dir do |dir|
415
+ missing = File.join(dir, 'Nope', 'ask', 'Default_x.chat')
416
+ worker_log = receipt_chat_text(
417
+ {'d1' => [meta_receipt("job=#{missing}")]}
418
+ )
419
+ worker = make_job(dir, 'Planned/work/Default_wd',
420
+ logs: {'agent.chat' => worker_log})
421
+
422
+ out, err, status = prov(worker)
423
+ assert status.success?, 'a dangling pointer must never abort rendering'
424
+ assert_include err, 'agent_meta receipt:', err
425
+ assert_include err, 'unresolved_job_reference', err
426
+ assert_include err, 'Default_x', err
427
+ assert_match(/\A job Default_wd/, out)
428
+ assert_not_include out, 'Default_x'
429
+ end
430
+ end
431
+
432
+
433
+ # ---- Phase 10: reworked accounting/presentation contract ---------------
434
+
435
+ # 1 + 2 + 3: cache rate from RAW integers (rounding boundary pt=1_999_999
436
+ # cct=1_000_000 -> 50.0%), fresh only in the footer, canonical field order.
437
+ def test_footer_cache_rate_and_fresh_from_raw_integers
438
+ TmpFile.with_dir do |dir|
439
+ chat = write_chat(dir, 'round.chat',
440
+ "user: hi\n" +
441
+ "meta: pt=1999999 ct=1 tt=2000000 cct=1000000 inference_id=r1 timestamp=2026-09-04T00:00:00Z\n" +
442
+ "meta: pt=0 ct=1 tt=500 inference_id=r2 timestamp=2026-09-04T00:00:00Z\n" +
443
+ "assistant: ok\n")
444
+
445
+ out, _err, status = prov(chat)
446
+ assert status.success?
447
+
448
+ node_line = out.lines.find { |line| line.include?('round.chat') }
449
+ footer = out.lines.find { |line| line.start_with?('root') }
450
+ assert footer, out
451
+
452
+ # Raw-integer rate on both node and footer: 100.0 * 1000000/1999999
453
+ # is 50.00002... -> '50.0'. The humanized absolute stays compact.
454
+ assert_include node_line, 'prompt=2M cache=1M@50.0%', node_line
455
+ assert_include footer, 'cache=1M@50.0%', footer
456
+
457
+ # fresh is footer-only, raw pt - cct, humanized.
458
+ assert_include footer, 'fresh=1M', footer
459
+ assert_not_include node_line, 'fresh=', 'fresh must not appear on node lines'
460
+
461
+ # Canonical field order on both lines.
462
+ assert_match(/chat evidence=2M prompt=2M cache=1M@50\.0% cont=2 round\.chat/,
463
+ node_line, out)
464
+ assert_match(/\Aroot deduplicated_total=2M \(2 events\) prompt=2M cache=1M@50\.0% fresh=1M cont=2 /,
465
+ footer, out)
466
+
467
+ # The pt=0 event contributes tt and ct but no prompt-axis field.
468
+ assert_include footer, 'cont=2', footer
469
+
470
+ # cache_write= only when cwt>0: absent here.
471
+ assert_not_include out, 'cache_write=', out
472
+
473
+ # The case2 shape (tmp/prov-rework/case2): pt=20M cct=19M -> 95.0%.
474
+ case2 = write_chat(dir, 'case2.chat',
475
+ "user: hi\n" +
476
+ "meta: pt=20000000 ct=800 tt=20000800 cct=19000000 rt=600 " \
477
+ "inference_id=c2 timestamp=2026-09-04T00:00:00Z\n" +
478
+ "assistant: ok\n")
479
+ out3, _err3, status3 = prov(case2)
480
+ assert status3.success?
481
+ assert_include out3, 'prompt=20M cache=19M@95.0% cont=800 reason=600', out3
482
+ footer2 = out3.lines.find { |line| line.start_with?('root') }
483
+ assert_include footer2, 'cache=19M@95.0% fresh=1M', footer2
484
+ end
485
+ end
486
+
487
+ # 2: fresh includes the cache-write portion (cwt is not subtracted from pt).
488
+ # 3: cache_write= prints only when cwt>0.
489
+ def test_footer_fresh_includes_cache_write_and_cache_write_gated
490
+ TmpFile.with_dir do |dir|
491
+ _a, _b, _c, _tsv, _parent = continuation_chain(dir)
492
+ out, _err, status = prov(_a)
493
+ assert status.success?
494
+
495
+ footer = out.lines.find { |line| line.start_with?('root') }
496
+ assert footer, out
497
+ # A's own metas: pt=120, cct=90, cwt=15 -> fresh=120-90=30, cache_write=15.
498
+ assert_include footer, 'prompt=120 cache=90@75.0% fresh=30 cache_write=15', footer
499
+
500
+ # Node lines never carry fresh= or cache_write=.
501
+ node = out.lines.find { |line| line =~ /\A job\b/ }
502
+ assert node, out
503
+ assert_not_include node, 'fresh=', node
504
+ assert_not_include node, 'cache_write=', node
505
+ end
506
+ end
507
+
508
+ # 4: -c direct= values come from the node's own log sums (cumulative ask
509
+ # shape: the continuation job's direct log carries the projected parent
510
+ # metas inlined, so direct= still equals its full recorded log).
511
+ def test_component_direct_values_from_local_log_sums
512
+ TmpFile.with_dir do |dir|
513
+ a, b, c, _tsv, _parent = continuation_chain(dir)
514
+
515
+ out, _err, status = prov('--component', a)
516
+ assert status.success?
517
+ line_a = out.lines.find { |line| line =~ /\A job\b/ }
518
+ assert_include line_a, 'direct=150', line_a
519
+ assert_not_include line_a, 'evidence=', line_a
520
+
521
+ out, _err, status = prov('--component', b)
522
+ assert status.success?
523
+ line_b = out.lines.find { |line| line =~ /\A job\b/ }
524
+ assert_include line_b, 'direct=390', 'B log = 3 parent metas + 2 own, each tt=50 or 120'
525
+
526
+ out, _err, status = prov('--component', c)
527
+ assert status.success?
528
+ line_c = out.lines.find { |line| line =~ /\A job\b/ }
529
+ assert_include line_c, 'direct=990', 'C log = cumulative history, 6 events'
530
+ end
531
+ end
532
+
533
+ # 5 + 11: delta= on job nodes in BOTH modes; absent on chat nodes and for
534
+ # non-chat results.
535
+ def test_delta_visibility_in_both_modes_and_omissions
536
+ TmpFile.with_dir do |dir|
537
+ a, b, c, tsv, parent = continuation_chain(dir)
538
+
539
+ ['', '-c'].each do |mode|
540
+ out, _err, status = prov(*(mode.empty? ? [c] : ['--component', c]))
541
+ assert status.success?, mode
542
+ job_c = out.lines.find { |line| line =~ /Default_c3/ && line =~ /\A job\b/ }
543
+ job_b = out.lines.find { |line| line =~ /Default_b2/ && line =~ /\A\s*job\b/ }
544
+ assert_include job_c, 'delta=600', job_c
545
+ assert_include job_b, 'delta=240', job_b
546
+
547
+ # The TSV-typed job (receipt child of parent.chat) omits delta=, and
548
+ # the plain chat node never carries it.
549
+ out2, _err2, status2 = prov(*(mode.empty? ? [parent] : ['--component', parent]))
550
+ assert status2.success?, mode
551
+ chat_line = out2.lines.find { |line| line.include?('parent.chat') }
552
+ assert_not_include chat_line, 'delta=', chat_line
553
+ tsv_line = out2.lines.find { |line| line =~ /Default_d4/ }
554
+ assert tsv_line, out2
555
+ assert_not_include tsv_line, 'delta=', 'non-chat result must omit delta=, not print delta=0'
556
+ end
557
+ end
558
+ end
559
+
560
+ # 6: footer equals the collector deduplicated scope; footer present in -c
561
+ # without receipts (covered by plain.chat in test_component_mode...).
562
+ def test_footer_equals_collector_deduplicated_total_on_chain
563
+ TmpFile.with_dir do |dir|
564
+ _a, _b, c, _tsv, parent = continuation_chain(dir)
565
+ [c, parent].each do |root|
566
+ expected = Chat.provenance_token_totals(root)
567
+ out, _err, status = prov(root)
568
+ assert status.success?
569
+ assert_match(/root deduplicated_total=#{expected[:tt]} /, out)
570
+ # Cross-consumer: the per-node root line also carries the closure.
571
+ root_line = out.lines.find { |line| line =~ /\A (job|chat)\b/ }
572
+ assert_include root_line, "evidence=#{expected[:tt]}", root_line
573
+ assert_equal expected, Chat.tokens(root)
574
+ end
575
+ end
576
+ end
577
+
578
+ # 9: continuation chain additivity: sum of per-job deltas equals the root
579
+ # footer deduplicated_total; ancestor evidence= closures are cumulative.
580
+ def test_chain_deltas_sum_to_footer_and_closures_cumulative
581
+ TmpFile.with_dir do |dir|
582
+ _a, _b, c, _tsv, _parent = continuation_chain(dir)
583
+
584
+ out, _err, status = prov(c)
585
+ assert status.success?
586
+
587
+ # Cumulative closures down the chain: A 150 < B 390 < C 990.
588
+ assert_match(/job evidence=150 .*Default_a1/, out)
589
+ assert_match(/job evidence=390 .*Default_b2/, out)
590
+ assert_match(/job evidence=990 .*Default_c3/, out)
591
+
592
+ # Deltas are disjoint and sum to the footer: 150 + 240 + 600 = 990.
593
+ deltas = out.lines.select { |line| line =~ /job\b/ && line =~ /evidence=/ }
594
+ .collect { |line| line[/delta=(\d+)/, 1].to_i }
595
+ # Tree order is root-first: C, B, A.
596
+ assert_equal [600, 240, 150], deltas, out
597
+ assert_equal deltas.sum, 990
598
+ assert_match(/root deduplicated_total=990 \(6 events\)/, out)
599
+
600
+ # Same additivity holds in -c mode.
601
+ out_c, _err_c, status_c = prov('--component', c)
602
+ assert status_c.success?
603
+ deltas_c = out_c.lines.select { |line| line =~ /job\b/ && line =~ /direct=/ }
604
+ .collect { |line| line[/delta=(\d+)/, 1].to_i }
605
+ assert_equal deltas, deltas_c
606
+ assert_match(/root deduplicated_total=990 /, out_c)
607
+ end
608
+ end
609
+
610
+ # 10: zero/missing cache and pt=0 omission (no exception, no prompt axis).
611
+ def test_zero_cache_and_missing_prompt_axis
612
+ TmpFile.with_dir do |dir|
613
+ _a, _b, _c, _tsv, parent = continuation_chain(dir)
614
+
615
+ # cct=0 with pt>0: cache=0@0.0% and footer fresh=<pt>.
616
+ out, _err, status = prov(parent)
617
+ assert status.success?
618
+ footer = out.lines.find { |line| line.start_with?('root') }
619
+ assert footer, out
620
+ assert_include footer, 'prompt=17 cache=0@0.0% fresh=17', footer
621
+
622
+ # pt=0 everywhere: the whole prompt axis disappears, tt still prints.
623
+ zero = write_chat(dir, 'zero.chat',
624
+ "user: hi\nmeta: pt=0 ct=1 tt=500 inference_id=z1 timestamp=2026-09-04T00:00:00Z\nassistant: ok\n")
625
+ out2, _err2, status2 = prov(zero)
626
+ assert status2.success?, 'pt=0 must not raise'
627
+ assert_include out2, 'chat evidence=500 cont=1 zero.chat', out2
628
+ assert_match(/root deduplicated_total=500 \(1 events\) cont=1 /, out2)
629
+ %w[prompt= cache= fresh= cache_write= @].each do |token|
630
+ assert_not_include out2, token, "pt=0 must omit the whole prompt axis: #{token}"
631
+ end
632
+ end
633
+ end
634
+
635
+ # 12: identity conflicts produce the footer caveat in both modes; no
636
+ # conflicts means no caveat line.
637
+ def test_conflict_caveat_lives_in_footer_in_both_modes
638
+ TmpFile.with_dir do |dir|
639
+ # Same inference_id recorded with two different tt: a conflict.
640
+ conflicting = write_chat(dir, 'conflict.chat',
641
+ "user: hi\n" +
642
+ "meta: pt=10 ct=1 tt=11 inference_id=k1 timestamp=2026-09-04T00:00:00Z provider_response_id=p1\n" +
643
+ "meta: pt=10 ct=1 tt=99 inference_id=k1 timestamp=2026-09-04T00:00:00Z provider_response_id=p1\n" +
644
+ "assistant: ok\n")
645
+
646
+ ['', '-c'].each do |mode|
647
+ out, _err, status = prov(*(mode.empty? ? [conflicting] : ['--component', conflicting]))
648
+ assert status.success?, mode
649
+ caveat = out.lines.count { |line| line.include?('not exact') }
650
+ assert_equal 1, caveat, "caveat must come from the footer once: #{mode}\n#{out}"
651
+ assert_include out, 'unresolved identity conflicts', out
652
+ end
653
+
654
+ # No conflicts: no caveat line at all.
655
+ clean = write_chat(dir, 'clean.chat',
656
+ "user: hi\nmeta: pt=10 ct=1 tt=11 inference_id=q1 timestamp=2026-09-04T00:00:00Z\nassistant: ok\n")
657
+ out, _err, status = prov(clean)
658
+ assert status.success?
659
+ assert_not_include out, 'not exact', out
660
+ end
661
+ end
662
+
663
+ # 8: saved+receipt dedup: the merged event is counted once in the scope
664
+ # block and the footer equals the collector total.
665
+ def test_saved_and_receipt_dedup_scope_and_footer
666
+ TmpFile.with_dir do |dir|
667
+ parent, _worker = fixture_b(dir)
668
+ expected = Chat.provenance_token_totals(parent)
669
+
670
+ out, _err, status = prov('--component', parent)
671
+ assert status.success?
672
+
673
+ # w1/w2 are stored in the worker log AND in the parent receipt: chat
674
+ # and receipt scopes both cover them, deduplicated_total counts once.
675
+ assert_match(/evidence chat_evidence: total=#{expected[:tt]}/, out)
676
+ assert_match(/evidence receipt_evidence: total=180/, out)
677
+ assert_match(/evidence receipt_only: total=0/, out)
678
+ assert_match(/root deduplicated_total=#{expected[:tt]} /, out)
679
+
680
+ # Scope block is exactly 3 lines now.
681
+ scope_lines = out.lines.count { |line| line =~ /^\s*evidence \w+:/ }
682
+ assert_equal 3, scope_lines, out
683
+ end
684
+ end
685
+
686
+ # ---- Short-form jobname labels (delegated-job presentation) ------------
687
+ #
688
+ # Jobname-when-not-Default rule: a delegated job whose jobname differs from
689
+ # the `Default` sentinel labels with the jobname; a Default-named job keeps
690
+ # the historical hash-excerpt label.
691
+ def test_named_delegated_job_labels_with_jobname
692
+ TmpFile.with_dir do |dir|
693
+ child = make_job(dir, 'Cortex/continue/echo-worker_f44dbdeb0c47d569454e8276ea39de5e.chat',
694
+ info: {workflow: 'Cortex', task_name: 'continue', clean_name: 'echo-worker'})
695
+ worker_log = receipt_chat_text({'n1' => [meta_receipt("job=#{child}")]})
696
+ worker = make_job(dir, 'Planned/work/Default_wn',
697
+ info: {workflow: 'Planned', task_name: 'work'},
698
+ logs: {'agent.chat' => worker_log})
699
+
700
+ out, err, status = prov(worker)
701
+ assert status.success?, err
702
+ assert_match(/job delegated-job Cortex\/continue echo-worker\b/, out)
703
+ # The hash excerpt is no longer the label token for a named job.
704
+ assert_not_include out, 'Cortex/continue f44dbdeb'
705
+ end
706
+ end
707
+
708
+ def test_default_named_job_keeps_hash_excerpt_label
709
+ TmpFile.with_dir do |dir|
710
+ child = make_job(dir, 'Cortex/continue/Default_f44dbdeb0c47d569454e8276ea39de5e.chat',
711
+ info: {workflow: 'Cortex', task_name: 'continue', clean_name: 'Default'})
712
+ worker_log = receipt_chat_text({'d1' => [meta_receipt("job=#{child}")]})
713
+ worker = make_job(dir, 'Planned/work/Default_wd2',
714
+ info: {workflow: 'Planned', task_name: 'work'},
715
+ logs: {'agent.chat' => worker_log})
716
+
717
+ out, err, status = prov(worker)
718
+ assert status.success?, err
719
+ assert_match(/job delegated-job Cortex\/continue f44dbdeb\b/, out)
720
+ assert_not_include out, 'Cortex/continue Default'
721
+ end
722
+ end
723
+
724
+ # A failed named job produces a bare delegated-job line (no evidence/cost
725
+ # fields, since it contributed no tokens) carrying its jobname.
726
+ def test_failed_named_job_renders_bare_delegated_line_with_name
727
+ TmpFile.with_dir do |dir|
728
+ child = make_job(dir, 'Cortex/continue/cortex-bad-brief_11111111111111111111111111111111.chat',
729
+ result: {exception: 'boom'}.to_json,
730
+ info: {workflow: 'Cortex', task_name: 'continue',
731
+ clean_name: 'cortex-bad-brief', status: 'error'})
732
+ worker_log = receipt_chat_text({'f1' => [meta_receipt("job=#{child}")]})
733
+ worker = make_job(dir, 'Planned/work/Default_wf2',
734
+ info: {workflow: 'Planned', task_name: 'work'},
735
+ logs: {'agent.chat' => worker_log})
736
+
737
+ out, err, status = prov(worker)
738
+ assert status.success?, err
739
+ bare = out.lines.find { |line| line.include?('cortex-bad-brief') }
740
+ assert bare, out
741
+ assert_match(/\A\s*job delegated-job Cortex\/continue cortex-bad-brief\s*$/, bare)
742
+ %w[evidence= delta= prompt= cache= cont= reason=].each do |field|
743
+ assert_not_include bare, field, bare
744
+ end
745
+ end
746
+ end
747
+
748
+ # Two distinct jobs sharing one jobname stay distinguishable: each label
749
+ # carries the jobname plus its short hash.
750
+ def test_shared_jobname_disambiguated_with_short_hash
751
+ TmpFile.with_dir do |dir|
752
+ child1 = make_job(dir, 'Cortex/continue/echo-worker_f44dbdeb0c47d569454e8276ea39de5e.chat',
753
+ info: {workflow: 'Cortex', task_name: 'continue', clean_name: 'echo-worker'})
754
+ child2 = make_job(dir, 'Cortex/continue/echo-worker_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.chat',
755
+ info: {workflow: 'Cortex', task_name: 'continue', clean_name: 'echo-worker'})
756
+ worker_log = receipt_chat_text(
757
+ {'s1' => [meta_receipt("job=#{child1}"), meta_receipt("job=#{child2}")]}
758
+ )
759
+ worker = make_job(dir, 'Planned/work/Default_ws',
760
+ info: {workflow: 'Planned', task_name: 'work'},
761
+ logs: {'agent.chat' => worker_log})
762
+
763
+ out, err, status = prov(worker)
764
+ assert status.success?, err
765
+ assert_include out, 'Cortex/continue echo-worker f44dbdeb'
766
+ assert_include out, 'Cortex/continue echo-worker aaaaaaaa'
767
+ bare_lines = out.lines.select do |line|
768
+ line.include?('Cortex/continue echo-worker') &&
769
+ !line.include?('f44dbdeb') && !line.include?('aaaaaaaa')
770
+ end
771
+ assert_empty bare_lines, "no shared-name label without hash: #{bare_lines * ' | '}"
772
+ end
773
+ end
774
+
775
+ # Flow and dot share node_label, so the jobname rule reaches both; the flow
776
+ # table's separate id column keeps the hash.
777
+ def test_flow_and_dot_show_jobname_label
778
+ TmpFile.with_dir do |dir|
779
+ child = make_job(dir, 'Cortex/continue/echo-worker_f44dbdeb0c47d569454e8276ea39de5e.chat',
780
+ info: {workflow: 'Cortex', task_name: 'continue', clean_name: 'echo-worker'})
781
+ worker_log = receipt_chat_text({'fd1' => [meta_receipt("job=#{child}")]})
782
+ worker = make_job(dir, 'Planned/work/Default_wfd',
783
+ info: {workflow: 'Planned', task_name: 'work'},
784
+ logs: {'agent.chat' => worker_log})
785
+
786
+ out, _err, status = prov('--flow', worker)
787
+ assert status.success?
788
+ job_row = out.lines.find { |line| line =~ /Cortex\/continue/ }
789
+ assert job_row, out
790
+ assert_include job_row, 'Cortex/continue echo-worker'
791
+ assert_include job_row, 'f44dbdeb', "flow id column keeps the hash: #{job_row}"
792
+
793
+ dot_file = File.join(dir, 'prov.dot')
794
+ out2, _err2, status2 = prov('--dot', dot_file, worker)
795
+ assert status2.success?
796
+ assert_include File.read(dot_file), 'Cortex/continue echo-worker'
797
+ end
798
+ end
799
+
800
+
801
+ # ---- Short-form society chat labels ------------------------------------
802
+ #
803
+ # Society conversations saved under a `.society` directory label with
804
+ # `society <Agent>/<conversation>` derived from the LAST marker segment
805
+ # (`society` or any `<name>.society`), instead of their path. The rule is
806
+ # layout-based: it fires for chat-owned and job-owned societies alike, and
807
+ # in flow/dot output where the parent is unknown.
808
+ #
809
+ # Chat-owned society sidecar: compact pair, never the path.
810
+ def test_society_chat_labels_with_agent_conversation_pair
811
+ TmpFile.with_dir do |dir|
812
+ saved = write_chat(dir, 'saved.chat',
813
+ "user: hi\nmeta: pt=1 ct=1 tt=2 inference_id=s1\nassistant: done\n")
814
+ society_chat = File.join(saved + '.files', 'agent.society', 'Worker', 'mgr-social-smoke', 'agent.chat')
815
+ FileUtils.mkdir_p(File.dirname(society_chat))
816
+ File.write(society_chat,
817
+ "user: work\nmeta: pt=5 ct=2 tt=7 inference_id=s2\nassistant: ok\n")
818
+
819
+ out, err, status = prov(saved)
820
+ assert status.success?, err
821
+
822
+ society_line = out.lines.find { |line| line.include?('society Worker/mgr-social-smoke') }
823
+ assert society_line, out
824
+ assert_match(/\A\s*chat\b/, society_line, out)
825
+ assert_include society_line, 'evidence=7', out
826
+ assert_not_include out, 'agent.society/Worker/mgr-social-smoke/agent.chat'
827
+ end
828
+ end
829
+
830
+ # -l still prints full paths: the society line is byte-identical to the
831
+ # pre-change rendering, so the long form is untouched.
832
+ def test_society_long_form_shows_full_path
833
+ TmpFile.with_dir do |dir|
834
+ saved = write_chat(dir, 'saved.chat',
835
+ "user: hi\nmeta: pt=1 ct=1 tt=2 inference_id=s1\nassistant: done\n")
836
+ society_chat = File.join(saved + '.files', 'agent.society', 'Worker', 'mgr-social-smoke', 'agent.chat')
837
+ FileUtils.mkdir_p(File.dirname(society_chat))
838
+ File.write(society_chat,
839
+ "user: work\nmeta: pt=5 ct=2 tt=7 inference_id=s2\nassistant: ok\n")
840
+
841
+ long_out, err, status = prov('-l', saved)
842
+ assert status.success?, err
843
+ long_line = long_out.lines.find { |line| line.include?(society_chat) }
844
+ assert long_line, long_out
845
+ assert_include long_line, 'agent.society/Worker/mgr-social-smoke/agent.chat'
846
+
847
+ short_out, _err, _status = prov(saved)
848
+ assert_not_include short_out, society_chat
849
+ assert_include short_out, 'society Worker/mgr-social-smoke'
850
+ end
851
+ end
852
+
853
+ # The same pair saved under two parents stays distinguishable through the
854
+ # short path digest (the digest the flow id column already shows).
855
+ def test_duplicate_society_pair_disambiguated_with_digest
856
+ TmpFile.with_dir do |dir|
857
+ saved = write_chat(dir, 'saved.chat',
858
+ "user: hi\nmeta: pt=1 ct=1 tt=2 inference_id=s1\nassistant: done\n")
859
+ first = File.join(saved + '.files', 'agent.society', 'Worker', 'default', 'agent.chat')
860
+ second = File.join(saved + '.files', 'other.society', 'Worker', 'default', 'agent.chat')
861
+ [first, second].each do |path|
862
+ FileUtils.mkdir_p(File.dirname(path))
863
+ File.write(path, "user: work\nmeta: pt=5 ct=2 tt=7 inference_id=s2\nassistant: ok\n")
864
+ end
865
+
866
+ out, err, status = prov(saved)
867
+ assert status.success?, err
868
+
869
+ society_lines = out.lines.select { |line| line.include?('society Worker/default') }
870
+ assert_equal 2, society_lines.length, out
871
+ digests = society_lines.collect { |line| line[/society Worker\/default \(([0-9a-f]{8})\)/, 1] }
872
+ assert_equal 2, digests.compact.uniq.length, society_lines * "\n"
873
+ assert_equal [Misc.digest(first)[0, 8], Misc.digest(second)[0, 8]].sort, digests.sort
874
+
875
+ ambiguous = society_lines.reject { |line| line =~ /society Worker\/default \([0-9a-f]{8}\)/ }
876
+ assert_empty ambiguous, ambiguous * "\n"
877
+ end
878
+ end
879
+
880
+ # Nested societies label by their own agent/conversation: the LAST marker
881
+ # segment wins, both for the plain `society` basename and for the
882
+ # `<name>.society` sibling form of nested saves.
883
+ def test_nested_society_labels_by_last_marker
884
+ TmpFile.with_dir do |dir|
885
+ saved = write_chat(dir, 'saved.chat',
886
+ "user: hi\nmeta: pt=1 ct=1 tt=2 inference_id=s1\nassistant: done\n")
887
+ nested = File.join(saved + '.files', 'agent.society', 'Worker', 'w_A',
888
+ 'society', 'Critic', 'c_1', 'agent.chat')
889
+ sibling = File.join(saved + '.files', 'agent.society', 'Worker', 'w_B',
890
+ 'Worker.society', 'Critic', 'c_2', 'agent.chat')
891
+ [nested, sibling].each do |path|
892
+ FileUtils.mkdir_p(File.dirname(path))
893
+ File.write(path, "user: crit\nmeta: pt=3 ct=1 tt=4 inference_id=s3\nassistant: ok\n")
894
+ end
895
+
896
+ out, err, status = prov(saved)
897
+ assert status.success?, err
898
+ assert_include out, 'society Critic/c_1'
899
+ assert_include out, 'society Critic/c_2'
900
+ # The outer agent/conversation never leaks into the nested label.
901
+ assert_not_include out, 'society Worker/w_A'
902
+ assert_not_include out, 'society Worker/w_B'
903
+
904
+ # Flow and dot share node_label with no parent, so the compact pair
905
+ # reaches both automatically.
906
+ flow_out, _err, _status = prov('--flow', saved)
907
+ assert_include flow_out, 'society Critic/c_1'
908
+ dot_file = File.join(dir, 'prov.dot')
909
+ prov('--dot', dot_file, saved)
910
+ assert_include File.read(dot_file), 'society Critic/c_2'
911
+ end
912
+ end
913
+
914
+ # Job-owned societies get the compact label too, while ordinary job log
915
+ # chats (no marker segment) keep their basename rendering.
916
+ def test_job_log_children_and_job_owned_society_labels
917
+ TmpFile.with_dir do |dir|
918
+ job = make_job(dir, 'Cortex/continue/cortex-smoke_a8f0e48e0000000000000000000000000000.chat',
919
+ info: {workflow: 'Cortex', task_name: 'continue', clean_name: 'cortex-smoke'},
920
+ logs: {
921
+ 'Worker.chat' => "user: work\nmeta: pt=5 ct=2 tt=7 inference_id=w1\nassistant: ok\n",
922
+ 'agent.society/Worker/mgr-social-smoke/agent.chat' =>
923
+ "user: soc\nmeta: pt=4 ct=1 tt=5 inference_id=s1\nassistant: ok\n"
924
+ })
925
+
926
+ out, err, status = prov(job)
927
+ assert status.success?, err
928
+
929
+ # A log chat without a marker segment keeps the basename label.
930
+ worker_line = out.lines.find { |line| line.include?('Worker.chat') }
931
+ assert worker_line, out
932
+ assert_match(/\A\s*chat\b/, worker_line, out)
933
+ assert_not_include worker_line, 'society'
934
+
935
+ # The job-owned society conversation is compacted as well.
936
+ society_line = out.lines.find { |line| line.include?('society Worker/mgr-social-smoke') }
937
+ assert society_line, out
938
+ assert_match(/\A\s*chat\b/, society_line, out)
939
+ assert_not_include out, 'agent.society/Worker/mgr-social-smoke/agent.chat'
940
+ end
941
+ end
942
+
943
+ # Label changes must not touch accounting: the root footer stays byte
944
+ # identical between the pre- and post-change renderings of the same tree.
945
+ def test_society_tree_keeps_footer_accounting
946
+ TmpFile.with_dir do |dir|
947
+ saved = write_chat(dir, 'saved.chat',
948
+ "user: hi\nmeta: pt=1 ct=1 tt=2 inference_id=s1\nassistant: done\n")
949
+ society_chat = File.join(saved + '.files', 'agent.society', 'Worker', 'mgr-social-smoke', 'agent.chat')
950
+ FileUtils.mkdir_p(File.dirname(society_chat))
951
+ File.write(society_chat,
952
+ "user: work\nmeta: pt=5 ct=2 tt=7 inference_id=s2\nassistant: ok\n")
953
+
954
+ expected = Chat.provenance_token_totals(saved)
955
+
956
+ out, err, status = prov(saved)
957
+ assert status.success?, err
958
+
959
+ footer = out.lines.find { |line| line.start_with?('root deduplicated_total=') }
960
+ assert footer, out
961
+ assert_equal "root deduplicated_total=9 (2 events) prompt=6 cache=0@0.0% fresh=6 cont=3 " +
962
+ "(authoritative cost; per-node evidence=/direct= values overlap)",
963
+ footer.chomp, out
964
+ assert_equal expected[:tt], 9
965
+ assert_equal expected[:pt], 6
966
+ end
967
+ end
968
+
274
969
  end