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
@@ -21,8 +21,10 @@ $ #{cmd} [<options>] <filename>
21
21
  -f--flow Print a compact provenance flow
22
22
  -l--long Show full filesystem paths instead of abbreviated names
23
23
  -e--evidence List the deduplicated direct inference events and their evidence
24
+ --live Show live work: in-flight inference from the .jobs sidecar, agent logs and society trees, beyond the captured report
24
25
  --dot* Write the flow as Graphviz DOT
25
26
  -p--plot* Render the flow as svg, png, or pdf
27
+ --timeline* Render the execution timeline as svg, png, pdf, or dot
26
28
 
27
29
  Default-tree numbers are evidence= subtree-deduplicated closures: they overlap
28
30
  between nodes and are never per-part cost. Job nodes add delta= (direct tokens
@@ -43,8 +45,10 @@ component = options.delete(:component)
43
45
  flow = options.delete(:flow)
44
46
  dot_file = options.delete(:dot)
45
47
  plot_file = options.delete(:plot)
48
+ timeline_file = options.delete(:timeline)
46
49
  long = options.delete(:long)
47
50
  evidence = options.delete(:evidence)
51
+ live = options.delete(:live)
48
52
  filename = ARGV.first
49
53
  raise MissingParameterException, :filename if filename.nil?
50
54
 
@@ -61,19 +65,30 @@ job_evidence = Open.exists?(filename + '.info')
61
65
  root_type = job_evidence ? :job : :chat
62
66
  root = root_type == :job ? Step.load(filename) : Path.setup(File.expand_path(filename))
63
67
  warnings = []
64
- records = Chat.traverse_provenance(
65
- root,
66
- root_type: root_type,
67
- on_error: lambda do |error, kind, object, relation, reference|
68
- warnings << {
69
- error: error,
70
- kind: kind,
71
- object: object,
72
- relation: relation,
73
- reference: reference
74
- }
75
- end
76
- ).to_a
68
+
69
+ # With --live the run must still work when the root chat is not yet on disk:
70
+ # the caller's save_file is flushed only at round end, so a chat observed
71
+ # MID-round exists only as its `<base>.jobs` sidecar (transient workload
72
+ # snapshot) plus the child job tree. The live section does not depend on the
73
+ # transcript at all, so tolerate an absent root here instead of failing.
74
+ records =
75
+ if live && root_type == :chat && !File.file?(filename)
76
+ []
77
+ else
78
+ Chat.traverse_provenance(
79
+ root,
80
+ root_type: root_type,
81
+ on_error: lambda do |error, kind, object, relation, reference|
82
+ warnings << {
83
+ error: error,
84
+ kind: kind,
85
+ object: object,
86
+ relation: relation,
87
+ reference: reference
88
+ }
89
+ end
90
+ ).to_a
91
+ end
77
92
 
78
93
  # ------------------------------------------------------------------
79
94
  # Build graph: nodes keyed by [kind, path], edges as {from, to, relation}
@@ -98,6 +113,116 @@ records.each do |kind, object, parent_kind, parent, relation, first_visit, _deta
98
113
  end
99
114
  root_key = Chat.provenance_key(root_type, root)
100
115
 
116
+ # ------------------------------------------------------------------
117
+ # Live section machinery (--live): render the unified live report
118
+ # ------------------------------------------------------------------
119
+ # Captured ids: the job references the forensic report already resolves.
120
+ # Taken from the SAME traversal records this script renders - :job edges
121
+ # (chat.jobs metas) and :agent_job edges (receipts) - so the live section
122
+ # never re-defines "captured"; whatever the normal report shows as a job
123
+ # node counts as captured. Both the Step#path form and the raw reference
124
+ # string form are included because live entries carry the sidecar's short
125
+ # form while edges carry Step objects.
126
+ captured_references = records.collect do |kind, object, parent_kind, _parent, relation, _first|
127
+ next nil unless parent_kind == :chat && kind == :job
128
+ next nil unless relation == :job || relation == :agent_job
129
+ [object.respond_to?(:path) ? object.path.to_s : object.to_s]
130
+ end.compact.flatten
131
+
132
+ # One renderer for both call sites (appended section after the normal
133
+ # report, and the --live-only fallback below), so the two cannot diverge.
134
+ # Renders nothing - not even the header - when nothing is live: `--live`
135
+ # output then equals the normal report exactly.
136
+ render_live_section = lambda do |live_base|
137
+ report = Chat.live_report(live_base, captured: captured_references)
138
+ entries = report[:entries]
139
+ next if entries.empty?
140
+
141
+ puts
142
+ puts 'Live work (in-flight while this prov run executes)'
143
+ puts '================================================='
144
+ # Stable order: kind first (inference before dangling_job before the
145
+ # rest - LIVE_KIND_ORDER below), then identifying path.
146
+ LIVE_KIND_ORDER = {inference: 0, dangling_job: 1, agent_activity: 2, workload_context: 3}
147
+ entries.sort_by! do |entry|
148
+ [LIVE_KIND_ORDER[entry[:kind]] || 99, entry[:path].to_s]
149
+ end
150
+ entries.each do |entry|
151
+ kind = LIVE_KIND_LABEL[entry[:kind]] || entry[:kind].to_s
152
+ # The identifying reference: the job's short path when the entry has
153
+ # one, else the agent-log path.
154
+ reference = entry[:reference].to_s
155
+ reference = entry[:agent_file].to_s if reference.empty?
156
+ detail = entry[:reason] || entry[:state]
157
+ detail = 'crashed/stale' if detail == :crashed
158
+ detail = detail.to_s if detail.is_a?(Symbol)
159
+ sources = [entry[:source]].flatten.compact.uniq.collect(&:to_s) * ','
160
+ extra = []
161
+ extra << "log=#{entry[:agent_log]}" if entry[:agent_log] && entry[:agent_log] != reference
162
+ extra << "info=#{entry[:status]}" if entry[:status]
163
+ line = format(' %-12s %-40s %-14s %-18s', kind, reference, detail, sources)
164
+ line += ' ' + extra.join(' ') unless extra.empty?
165
+ puts line
166
+ end
167
+ end
168
+ LIVE_KIND_LABEL = {inference: 'chat_task', dangling_job: 'dangling_job',
169
+ agent_activity: 'agent_active', workload_context: 'workflow'}
170
+
171
+ # Job nodes whose jobname (Step#clean_name) is not the `Default` sentinel
172
+ # label with the jobname instead of the input-hash excerpt. Jobnames are not
173
+ # unique: a conversation continued twice shares one jobname, so names used by
174
+ # more than one job node of this tree are disambiguated by appending the short
175
+ # hash. Counted once here, before any rendering, so tree, flow and dot modes
176
+ # disambiguate identically. A constant (like RELATION_ORDER below) because
177
+ # node_label is a def, and defs cannot close over top-level locals.
178
+ # An empty graph (records == [], the --live-only case for a chat that is not
179
+ # yet on disk) has nothing to label or render: skip the pre-render passes and
180
+ # every rendering mode below rather than dereferencing a missing root node.
181
+ if nodes.empty?
182
+ # --live with a chat that is not yet on disk: no transcript, but the
183
+ # sidecar, the agent save file and the job tree are real evidence.
184
+ # Routed through the same shared renderer the normal path appends, so
185
+ # the two paths cannot diverge.
186
+ render_live_section.call(root) if live
187
+ exit 0
188
+ end
189
+
190
+ JOB_NAME_COUNTS = Hash.new(0)
191
+ nodes.each_value do |node|
192
+ next unless node[:kind] == :job
193
+ job = node[:object]
194
+ name = job.respond_to?(:clean_name) ? job.clean_name : nil
195
+ JOB_NAME_COUNTS[name] += 1 if name && name != Task::DEFAULT_NAME
196
+ end
197
+
198
+ # Society conversations saved under a `.society` directory (agent.society at
199
+ # the top level, plain `society` or `<name>.society` for nested saves) label
200
+ # with their `<Agent>/<conversation>` pair instead of the path. The pair is
201
+ # taken after the LAST marker segment, so a nested save is labeled by its own
202
+ # agent/conversation rather than the outer one. Pairs are not unique either:
203
+ # the same conversation may be saved under two parents, so pairs used by more
204
+ # than one chat node are disambiguated by appending the short path digest
205
+ # (the same digest the flow id column shows for chats). Counted in the same
206
+ # pre-render pass as the jobname counts so tree, flow and dot modes label
207
+ # identically. A constant for the counts, like JOB_NAME_COUNTS above,
208
+ # because node_label is a def and defs cannot close over top-level locals.
209
+ def society_label_pair(path)
210
+ segments = path.split(File::SEPARATOR)
211
+ marker = segments.rindex do |segment|
212
+ segment == 'society' || segment.end_with?('.society')
213
+ end
214
+ return nil unless marker
215
+ agent, conversation = segments.values_at(marker + 1, marker + 2)
216
+ agent && conversation ? "#{agent}/#{conversation}" : nil
217
+ end
218
+
219
+ SOCIETY_LABEL_COUNTS = Hash.new(0)
220
+ nodes.each_value do |node|
221
+ next unless node[:kind] == :chat
222
+ pair = society_label_pair(node[:path])
223
+ SOCIETY_LABEL_COUNTS[pair] += 1 if pair
224
+ end
225
+
101
226
  # Adjacency: parent -> children, sorted for readability
102
227
  adjacency = Hash.new { |h, k| h[k] = [] }
103
228
  edges.each do |edge|
@@ -213,20 +338,16 @@ node_tokens = component ? direct_tokens : aggregate_tokens
213
338
  # Hidden nodes are skipped entirely — not printed and not traversed.
214
339
  # - result-relation chats: they duplicate the job node and create cycles
215
340
  # - top-level agent.chat log file: its cost is subsumed by the parent job.
216
- # ScoutCoder: DUAL-LAYOUT. The root copy of the agent conversation sits
217
- # directly under the files dir in BOTH layouts:
218
- # new <job>.files/agent.chat
219
- # legacy <job>.files/log/agent.chat
220
- # Any basename agent.chat whose parent is a `<something>.files` directory
221
- # (top level of the files dir) or the legacy `.../log` directory is such a
222
- # copy. NESTED society chats (agent.society/<agent>/<conv>/agent.chat,
223
- # log/society/<agent>/<conv>/agent.chat) are real independent inferences
224
- # and must be shown.
341
+ # The root copy of the agent conversation sits directly under the files
342
+ # dir (<job>.files/agent.chat): any basename agent.chat whose parent is a
343
+ # `<something>.files` directory is such a copy. NESTED society chats
344
+ # (agent.society/<agent>/<conv>/agent.chat) are real independent inferences
345
+ # and must be shown. The legacy `.files/log` tree is no longer traversed
346
+ # at all.
225
347
  def top_level_agent_chat?(path)
226
348
  return false unless File.basename(path) == 'agent.chat'
227
349
  parent = File.dirname(path)
228
- parent.end_with?('/log') || parent.end_with?('/log/') ||
229
- parent.end_with?('.files')
350
+ parent.end_with?('.files')
230
351
  end
231
352
 
232
353
  def hidden_node?(node, relation)
@@ -308,19 +429,26 @@ def node_label(node, parent_node = nil, root_key = nil, key = nil, long = false)
308
429
  workflow = job.info[:workflow] || job.info['workflow']
309
430
  task = job.info[:task_name] || job.info['task_name']
310
431
  short_id = job_short_id(path)
432
+ # Prefer the jobname over the hash excerpt; `Default` (and any step
433
+ # without a usable name) keeps the historical hash-only label. Shared
434
+ # jobnames get the short hash appended so the two nodes stay
435
+ # distinguishable in tree/flow/dot output.
436
+ name = job.respond_to?(:clean_name) ? job.clean_name : nil
437
+ if name && name != Task::DEFAULT_NAME
438
+ short_id = JOB_NAME_COUNTS[name] > 1 ? "#{name} #{short_id}" : name
439
+ end
311
440
  workflow && task ? "#{workflow}/#{task} #{short_id}" : short_id
312
- elsif parent_node && parent_node[:kind] == :job && path.include?('.files/log/')
313
- # Log chat under a job: show path relative to the job's log directory.
314
- # Derive log dir from parent_node path (which is the realpath) to avoid
315
- # symlink-resolution mismatches between the Step object and node path.
316
- parent_log_dir = File.join(parent_node[:path] + ".files", "log")
317
- rel = Misc.path_relative_to(parent_log_dir, path)
318
- rel.nil? || rel.empty? ? File.basename(path) : rel
441
+ elsif node[:kind] == :chat && (pair = society_label_pair(path))
442
+ # Saved society conversation: show the agent/conversation pair after the
443
+ # last `.society` marker instead of the path. Layout-based, so it fires
444
+ # for chat- and job-owned societies alike (and in flow/dot, where the
445
+ # parent is unknown). Non-unique pairs get the short digest appended.
446
+ SOCIETY_LABEL_COUNTS[pair] > 1 ? "society #{pair} (#{Misc.digest(path)[0, 8]})" : "society #{pair}"
319
447
  elsif parent_node && parent_node[:kind] == :job && path.include?(parent_node[:path] + '.files/')
320
- # ScoutCoder: DUAL-LAYOUT sibling of the legacy branch above. Log chat
321
- # under a job in the NEW layout (no log/ component): show the path
322
- # relative to the job's files dir, so
448
+ # Log chat under a job: show the path relative to the job's files dir, so
323
449
  # agent.society/Direct/harness_test/agent.chat is shown shortened.
450
+ # Derive files dir from parent_node path (which is the realpath) to avoid
451
+ # symlink-resolution mismatches between the Step object and node path.
324
452
  parent_files_dir = parent_node[:path] + '.files'
325
453
  rel = Misc.path_relative_to(parent_files_dir, path)
326
454
  rel.nil? || rel.empty? ? File.basename(path) : rel
@@ -335,7 +463,7 @@ end
335
463
  # ------------------------------------------------------------------
336
464
  # Tree rendering (default mode)
337
465
  # ------------------------------------------------------------------
338
- unless flow || dot_file || plot_file
466
+ unless flow || dot_file || plot_file || timeline_file
339
467
  printed = Set.new
340
468
  print_tree = lambda do |key, offset, relation, parent_key|
341
469
  # Skip already-visited nodes entirely (no "(seen)" line)
@@ -449,7 +577,7 @@ flow_edges = edges.collect do |edge|
449
577
  end
450
578
  end.uniq
451
579
 
452
- if flow || dot_file || plot_file
580
+ if flow || dot_file || plot_file || timeline_file
453
581
  # Determine visible nodes using same rules as tree mode.
454
582
  hidden_keys = Set.new
455
583
  nodes.each do |key, node|
@@ -509,31 +637,263 @@ if flow || dot_file || plot_file
509
637
  end
510
638
  end
511
639
 
512
- if dot_file || plot_file
640
+ if dot_file || plot_file || timeline_file
641
+ # ----------------------------------------------------------------
642
+ # Explanatory execution-flow dot (design: task/prov-svg-design-spec)
643
+ # ----------------------------------------------------------------
644
+ # The dot source explains the run instead of dumping it: labels carry
645
+ # names only, absolute paths live exclusively in tooltip= attributes
646
+ # (graphviz emits one <title> per node, shown on hover in svg), and
647
+ # the machine relation tokens survive only as class= attributes, so
648
+ # the legacy text greps keep passing without printing machine words in
649
+ # the figure. Shapes keep the historical job=box / chat=note
650
+ # contract; the one deliberate exception is the root, which swaps its
651
+ # note for a dominant inverted box pinned to the source rank.
513
652
  ids = ordered_keys.each_with_index.to_h { |key, index| [key, "n#{index}"] }
514
- lines = [
515
- 'digraph scout_ai_provenance {',
516
- ' graph [rankdir=LR, bgcolor="white", pad=0.2, nodesep=0.35, ranksep=0.6];',
517
- ' node [fontname="Helvetica", fontsize=10];',
518
- ' edge [fontname="Helvetica", fontsize=8, arrowsize=0.7];'
519
- ]
520
- ordered_keys.each do |key|
521
- node = nodes[key]
522
- label = "#{node[:kind].to_s.capitalize}\n#{node_label(node, nil, nil, key, long)}\n#{short_number(node_tokens.call(key)[:tt])} tokens"
523
- shape = node[:kind] == :job ? 'box' : 'note'
524
- lines << %( #{ids[key]} [shape=#{shape}, style="rounded,filled", fillcolor="#f7f7f7", label=#{JSON.generate(label)}];)
525
- end
526
- styles = {
527
- result: 'color="#39804a", penwidth=1.5, label="result"',
528
- delegated_result: 'color="#8a6d3b", penwidth=1.2, label="delegated_result"',
529
- dependency: 'color="#333333", label="dependency"',
530
- log: 'color="#2864a5", style="dashed", label="log"'
531
- }
653
+
654
+ # Flow-edge semantics, in data-flow direction:
655
+ # :delegated_result job -> parent chat (agent_meta receipt): the
656
+ # chat delegated to the job, rendered chat -> job.
657
+ # :result job -> chat that references it (meta: job=
658
+ # line): also a delegation, rendered chat -> job.
659
+ # A :result edge whose endpoints SHARE a path is
660
+ # instead the job's own chat-typed result
661
+ # (job_result_chat_file returns job.path itself),
662
+ # whose node is hidden above as a job duplicate;
663
+ # that identity pair is dropped, never drawn.
664
+ # :log parent -> chat. A job parent means the chat is
665
+ # an artifact the job produced (produces edge); a
666
+ # chat parent is a saved sidecar conversation,
667
+ # kept visually secondary (dashed, unlabeled).
668
+ # :dependency dependency job -> depending job: the dependency
669
+ # produced the job's input.
670
+ delegates = []
671
+ produces = []
672
+ log_edges = []
673
+ dependency_edges = []
532
674
  flow_edges.each do |edge|
533
- next unless visible_set.include?(edge[:from]) && visible_set.include?(edge[:to])
534
- lines << %( #{ids[edge[:from]]} -> #{ids[edge[:to]]} [#{styles[edge[:relation]] || "label=#{JSON.generate(edge[:relation].to_s)}"}];)
675
+ from, to, relation = edge.values_at(:from, :to, :relation)
676
+ next unless visible_set.include?(from) && visible_set.include?(to)
677
+ case relation
678
+ when :delegated_result, :result
679
+ next if nodes[from][:path] == nodes[to][:path]
680
+ delegates << {from: to, to: from}
681
+ when :log
682
+ if nodes[from][:kind] == :job
683
+ produces << {from: from, to: to}
684
+ else
685
+ log_edges << {from: from, to: to}
686
+ end
687
+ when :dependency
688
+ dependency_edges << {from: from, to: to}
689
+ end
690
+ end
691
+ delegates.uniq!
692
+ produces.uniq!
693
+ log_edges.uniq!
694
+ dependency_edges.uniq!
695
+ produced_keys = Set.new(produces.collect { |edge| edge[:to] })
696
+
697
+ # Continuation chains: jobs sharing a jobname (Step#clean_name) are
698
+ # turns of one conversation continued in place; mtime order is the
699
+ # operative signal, since every turn rewrites a longer chat. Chains
700
+ # render as flat arcs between consecutive turns, port-pinned south to
701
+ # north so they thread the gap between adjacent turns instead of
702
+ # competing with delegates (west) and produces (east) for ports;
703
+ # constraint=false keeps them from adding rank constraints.
704
+ chain_turns = {}
705
+ continues = []
706
+ chain_members = []
707
+ name_groups = Hash.new { |hash, name| hash[name] = [] }
708
+ visible_keys.each do |key|
709
+ next unless nodes[key][:kind] == :job
710
+ job = nodes[key][:object]
711
+ name = job.respond_to?(:clean_name) ? job.clean_name : nil
712
+ next if name.nil? || name == Task::DEFAULT_NAME
713
+ name_groups[name] << key
714
+ end
715
+ name_groups.each do |name, keys|
716
+ next unless keys.length >= 2
717
+ ordered = keys.sort_by do |key|
718
+ mtime = begin
719
+ File.mtime(nodes[key][:path])
720
+ rescue StandardError
721
+ Time.at(0)
722
+ end
723
+ [mtime, nodes[key][:path]]
724
+ end
725
+ ordered.each_with_index { |key, index| chain_turns[key] = index + 1 }
726
+ ordered.each_cons(2) { |first, second| continues << {from: first, to: second} }
727
+ # Cluster membership: the chain's jobs plus the chats those jobs
728
+ # produced, and nothing else; groups of one stay unclustered.
729
+ members = ordered.reject { |key| key == root_key }
730
+ members += produces.select { |edge| members.include?(edge[:from]) }
731
+ .collect { |edge| edge[:to] }
732
+ chain_members << [name, members]
733
+ end
734
+
735
+ # Job label line 1 keeps the node_label contract (workflow/task plus
736
+ # jobname); chain members trade the shared-name hash disambiguation
737
+ # for an explicit turn number, since the chain itself orders them.
738
+ job_label = lambda do |key|
739
+ turn = chain_turns[key]
740
+ base = node_label(nodes[key], nil, nil, key, long)
741
+ next base unless turn
742
+ job = nodes[key][:object]
743
+ info = job.respond_to?(:info) ? job.info : {}
744
+ workflow = info[:workflow] || info['workflow']
745
+ task = info[:task_name] || info['task_name']
746
+ name = job.respond_to?(:clean_name) ? job.clean_name : nil
747
+ core = name && name != Task::DEFAULT_NAME ? name : job_short_id(nodes[key][:path])
748
+ labelled = workflow && task ? "#{workflow}/#{task} #{core}" : core
749
+ "#{labelled} · turn #{turn}"
750
+ end
751
+
752
+ # Outcome before cost: an errored or aborted job shows its outcome and
753
+ # no token line (a zero figure would read as cost information the run
754
+ # does not have). Healthy jobs omit the token line only when there is
755
+ # nothing to show.
756
+ job_failed = lambda do |key|
757
+ job = nodes[key][:object]
758
+ info = job.respond_to?(:info) ? job.info : {}
759
+ status = info[:status] || info['status']
760
+ %w[error aborted].include?(status.to_s) || (job.respond_to?(:error?) && job.error?)
761
+ end
762
+
763
+ qualifier = component ? 'direct' : 'evidence'
764
+ node_lines = ordered_keys.collect do |key|
765
+ node = nodes[key]
766
+ path = node[:path]
767
+ tokens = node_tokens.call(key)[:tt]
768
+ badge = short_number(tokens)
769
+ label =
770
+ if key == root_key
771
+ lines = [node[:kind] == :chat ? File.basename(path) : job_label.call(key),
772
+ node[:kind] == :chat ? 'Root conversation' : 'Root job',
773
+ "#{qualifier} #{badge}"]
774
+ lines << '⚠ error' if node[:kind] == :job && job_failed.call(key)
775
+ lines
776
+ elsif node[:kind] == :job
777
+ lines = [job_label.call(key)]
778
+ if job_failed.call(key)
779
+ lines << '⚠ error'
780
+ elsif tokens > 0
781
+ lines << badge
782
+ end
783
+ lines
784
+ elsif society_label_pair(path)
785
+ [node_label(node, nil, nil, key, long), badge]
786
+ else
787
+ [File.basename(path), badge]
788
+ end
789
+ attrs =
790
+ if key == root_key
791
+ 'shape=box, class="prov-root", style="rounded,filled,bold", penwidth=2, ' \
792
+ 'fillcolor="#1F3A5F", color="#142A45", fontcolor="#FFFFFF", fontsize=14'
793
+ elsif node[:kind] == :job && job_failed.call(key)
794
+ 'shape=box, class="prov-job prov-error", style="rounded,filled", ' \
795
+ 'fillcolor="#FBE3E3", color="#C0392B", fontcolor="#8E2418"'
796
+ elsif node[:kind] == :job
797
+ 'shape=box, class="prov-job", style="rounded,filled", ' \
798
+ 'fillcolor="#DCE9F7", color="#4A7EBB", fontcolor="#1F3A5F"'
799
+ elsif society_label_pair(path)
800
+ 'shape=note, class="prov-society", style=filled, ' \
801
+ 'fillcolor="#F1F3F5", color="#9AA5B1", fontcolor="#5A6672"'
802
+ elsif produced_keys.include?(key)
803
+ 'shape=note, class="prov-chat", style=filled, ' \
804
+ 'fillcolor="#FFF6DC", color="#C9A227", fontcolor="#5C5236"'
805
+ else
806
+ 'shape=note, class="prov-chat", style=filled, ' \
807
+ 'fillcolor="#F1F3F5", color="#9AA5B1", fontcolor="#5A6672"'
808
+ end
809
+ format(' %s [%s, label=%s, tooltip=%s];',
810
+ ids[key], attrs, JSON.generate(label * "\n"), JSON.generate(path))
811
+ end
812
+
813
+ # Clusters carry the two groupings a reader needs: saved society
814
+ # conversations, and continuation chains with the artifacts their
815
+ # turns produced. A node joins at most one cluster.
816
+ cluster_blocks = []
817
+ clustered = Set.new
818
+ society_keys = ordered_keys.select do |key|
819
+ key != root_key && nodes[key][:kind] == :chat && society_label_pair(nodes[key][:path])
820
+ end
821
+ unless society_keys.empty?
822
+ clustered.merge(society_keys)
823
+ cluster_blocks << [
824
+ ' subgraph cluster_society {',
825
+ ' label="society chats (root logs)"; labeljust=l; fontsize=10; fontcolor="#5A6672";',
826
+ ' style="rounded,filled"; fillcolor="#F7F9FB"; color="#C7D0D9";',
827
+ ' ' + society_keys.collect { |key| ids[key] } * '; ' + ';',
828
+ ' }'
829
+ ] * "\n"
830
+ end
831
+ chain_members.sort_by { |name, _members| name }.each do |name, members|
832
+ members = members.reject { |key| clustered.include?(key) }
833
+ next if members.empty?
834
+ clustered.merge(members)
835
+ suffix = name.gsub(/[^A-Za-z0-9]/, '_')
836
+ suffix = "chain_#{suffix}" if suffix == 'society'
837
+ cluster_blocks << [
838
+ " subgraph cluster_#{suffix} {",
839
+ " label=\"#{name} continuation chain\"; labeljust=l; fontsize=10; fontcolor=\"#1F3A5F\";",
840
+ ' style="rounded,filled"; fillcolor="#F7F9FB"; color="#C7D0D9";',
841
+ ' ' + members.collect { |key| ids[key] } * '; ' + ';',
842
+ ' }'
843
+ ] * "\n"
535
844
  end
536
- lines << '}'
845
+
846
+ # Ranks: the root pinned to the source rank (leftmost in LR), every
847
+ # other job on one shared rank so delegation edges stay short and the
848
+ # chain arcs run flat between siblings; chats take the natural rank
849
+ # behind their producing job.
850
+ rank_blocks = [" {rank=source; #{ids[root_key]};}"]
851
+ job_ids = ordered_keys.select { |key| nodes[key][:kind] == :job && key != root_key }
852
+ .collect { |key| ids[key] }
853
+ rank_blocks << " {rank=same; #{job_ids * '; '};}" unless job_ids.empty?
854
+
855
+ edge_lines = []
856
+ delegates.each do |edge|
857
+ edge_lines << format(' %s -> %s [label="delegates", color="#1F3A5F", fontcolor="#1F3A5F", ' \
858
+ 'penwidth=1.6, class="delegated_result"];',
859
+ ids[edge[:from]], ids[edge[:to]])
860
+ end
861
+ produces.each do |edge|
862
+ edge_lines << format(' %s -> %s [label="produces", color="#4A7EBB", fontcolor="#4A7EBB", ' \
863
+ 'penwidth=1.1, class="dependency"];',
864
+ ids[edge[:from]], ids[edge[:to]])
865
+ end
866
+ continues.each do |edge|
867
+ edge_lines << format(' %s -> %s [label="continues", color="#6E5AA8", fontcolor="#6E5AA8", ' \
868
+ 'penwidth=1.3, constraint=false, tailport=s, headport=n];',
869
+ ids[edge[:from]], ids[edge[:to]])
870
+ end
871
+ dependency_edges.each do |edge|
872
+ edge_lines << format(' %s -> %s [label="result", color="#8A93A0", penwidth=0.9, ' \
873
+ 'class="dependency"];',
874
+ ids[edge[:from]], ids[edge[:to]])
875
+ end
876
+ log_edges.each do |edge|
877
+ edge_lines << format(' %s -> %s [style=dashed, color="#B0B7C3", penwidth=0.9];',
878
+ ids[edge[:from]], ids[edge[:to]])
879
+ end
880
+
881
+ lines = [
882
+ 'digraph scout_ai_provenance {',
883
+ ' graph [rankdir=LR, splines="spline", bgcolor="white", pad=0.25, nodesep=0.35, ranksep=0.8, ' \
884
+ 'fontname="Helvetica", fontsize=11];',
885
+ ' node [shape=box, style=filled, fontname="Helvetica", fontsize=11, margin="0.14,0.09"];',
886
+ ' edge [fontname="Helvetica", fontsize=9, fontcolor="#6B7280", arrowsize=0.8, color="#8A93A0"];',
887
+ '',
888
+ node_lines,
889
+ '',
890
+ cluster_blocks,
891
+ '',
892
+ rank_blocks,
893
+ '',
894
+ edge_lines,
895
+ '}'
896
+ ].flatten
537
897
  dot = lines * "\n"
538
898
  Open.write(dot_file, dot) if dot_file
539
899
 
@@ -548,6 +908,298 @@ if flow || dot_file || plot_file
548
908
  end
549
909
  end
550
910
  end
911
+
912
+ if timeline_file
913
+ # ----------------------------------------------------------------
914
+ # Execution-timeline dot (design: task/prov-svg-timeline-spec).
915
+ # ----------------------------------------------------------------
916
+ # The flow view answers "what delegated what"; this one answers
917
+ # "what happened when". The vertical axis IS the time axis: nodes
918
+ # are laid out in one single sequence ordered by the time model
919
+ # below, one node per rank, and every semantic edge is emitted with
920
+ # constraint=false so delegation topology can never stretch or
921
+ # reorder the axis. Only the spine (the chain of consecutive
922
+ # time-neighbours) carries constraint=true. Node classes, palette
923
+ # and tooltips are reused from the flow view unchanged; the deltas
924
+ # are the time line at label position 2, the transposed ports, the
925
+ # label policy (continues only) and the dropped society cluster.
926
+
927
+ # ---- Time model (spec S3), one priority list for order AND badges.
928
+ # Priority 1: the node's own chat file (job: its produced chat, the
929
+ # `produces` target; root: root.chat; society/other chats: their own
930
+ # file) parsed for meta records carrying `timestamp=` ISO-8601
931
+ # fields -> [first, last] interval. Priority 2: File.mtime of the
932
+ # node path -> point event, no duration. Tie-break on path, as the
933
+ # mtime ordering of the flow view does.
934
+ produced_chat_of = {}
935
+ produces.each { |edge| produced_chat_of[edge[:from]] = nodes[edge[:to]][:path] }
936
+ parse_iso = lambda do |value|
937
+ Time.iso8601(value.to_s)
938
+ rescue StandardError
939
+ nil
940
+ end
941
+ chat_interval = lambda do |path|
942
+ chat = begin
943
+ Chat.provenance_chat_load(path)
944
+ rescue StandardError
945
+ nil
946
+ end
947
+ return nil unless Array === chat
948
+ stamps = chat.filter_map do |message|
949
+ next unless message[:role].to_s == 'meta'
950
+ parse_iso.call(Chat.parse_meta(message[:content])[:timestamp])
951
+ end
952
+ return nil if stamps.empty?
953
+ [stamps.min, stamps.max]
954
+ end
955
+ node_time = lambda do |key|
956
+ path = nodes[key][:path]
957
+ chat_path = if key == root_key
958
+ nodes[key][:kind] == :chat ? path : Chat.job_result_chat_file(nodes[key][:object]).to_s
959
+ elsif nodes[key][:kind] == :job
960
+ produced_chat_of[key] || Chat.job_result_chat_file(nodes[key][:object]).to_s
961
+ else
962
+ path
963
+ end
964
+ interval = chat_path && Open.exists?(chat_path.to_s) ? chat_interval.call(chat_path) : nil
965
+ if interval
966
+ {start: interval[0], end: interval[1], source: :chat}
967
+ else
968
+ mtime = begin
969
+ File.mtime(path)
970
+ rescue StandardError
971
+ Time.at(0)
972
+ end
973
+ {start: mtime, end: mtime, source: :mtime}
974
+ end
975
+ end
976
+ time_of = {}
977
+ visible_keys.each { |key| time_of[key] = node_time.call(key) }
978
+ # Sequence: one priority list for order AND badges. The sort key is
979
+ # the full time key [start, end] with the path as final tie-break, so
980
+ # equal starts (cumulative continuation replays share their first
981
+ # stamp) still order by their end, which is exactly the chain
982
+ # (mtime) order the flow view's continuation arcs use. Ids are
983
+ # numbered along this sequence so n0 is the earliest event.
984
+ sequence = visible_keys.sort_by do |key|
985
+ [time_of[key][:start], time_of[key][:end], nodes[key][:path]]
986
+ end
987
+ ids = sequence.each_with_index.to_h { |key, index| [key, "n#{index}"] }
988
+ sequence_index = sequence.each_with_index.to_h { |key, index| [key, index] }
989
+
990
+ # Overlap flags (spec S3): pairwise [start,end) overlap of the
991
+ # node's own event, machine-checkable via class="prov-overlap".
992
+ overlap_keys = Set.new
993
+ sequence.each_with_index do |key, index|
994
+ interval = time_of[key]
995
+ ((index + 1)...sequence.length).each do |other|
996
+ candidate = time_of[sequence[other]]
997
+ next unless interval[:start] < candidate[:end] && candidate[:start] < interval[:end]
998
+ overlap_keys << key
999
+ overlap_keys << sequence[other]
1000
+ end
1001
+ end
1002
+
1003
+ # ---- Time line rendering (spec S4): `t=<HH:MM:SS>` point, or
1004
+ # `t=<HH:MM:SS>→<HH:MM:SS>` interval, optionally ` · <dur>`.
1005
+ format_clock = ->(time) { time.getlocal.strftime('%H:%M:%S') }
1006
+ format_duration = lambda do |seconds|
1007
+ seconds = seconds.to_i
1008
+ days, seconds = seconds.divmod(86_400)
1009
+ hours, seconds = seconds.divmod(3_600)
1010
+ minutes, seconds = seconds.divmod(60)
1011
+ return format('%dd', days) if days > 0
1012
+ return format('%dh%dm%ds', hours, minutes, seconds) if hours > 0
1013
+ return format('%dm%ds', minutes, seconds) if minutes > 0
1014
+ format('%ds', seconds)
1015
+ end
1016
+ time_line = lambda do |key|
1017
+ interval = time_of[key]
1018
+ clock = format_clock.call(interval[:start])
1019
+ return "t=#{clock}" if interval[:source] == :mtime || interval[:end] == interval[:start]
1020
+ "t=#{clock}→#{format_clock.call(interval[:end])} · #{format_duration.call(interval[:end] - interval[:start])}"
1021
+ end
1022
+
1023
+ # ---- Nodes: flow-view classes with the time line inserted at
1024
+ # position 2 (the badge keeps position 3; error jobs keep the
1025
+ # no-token-line rule).
1026
+ qualifier = component ? 'direct' : 'evidence'
1027
+ timeline_node_lines = sequence.collect do |key|
1028
+ node = nodes[key]
1029
+ path = node[:path]
1030
+ tokens = node_tokens.call(key)[:tt]
1031
+ badge = short_number(tokens)
1032
+ lines =
1033
+ if key == root_key
1034
+ # Spec S4: root label is name / time line / evidence badge; the
1035
+ # flow view's `Root conversation` caption is dropped (line 3 is
1036
+ # the badge, per T8).
1037
+ [node[:kind] == :chat ? File.basename(path) : job_label.call(key),
1038
+ time_line.call(key),
1039
+ "#{qualifier} #{badge}"]
1040
+ elsif node[:kind] == :job
1041
+ base = [job_label.call(key), time_line.call(key)]
1042
+ base << '⚠ error' if job_failed.call(key)
1043
+ base << badge if job_failed.call(key) == false && tokens > 0
1044
+ base
1045
+ elsif society_label_pair(path)
1046
+ [node_label(node, nil, nil, key, long), time_line.call(key), badge]
1047
+ else
1048
+ [File.basename(path), time_line.call(key), badge]
1049
+ end
1050
+ attrs =
1051
+ if key == root_key
1052
+ 'shape=box, class="prov-root", style="rounded,filled,bold", penwidth=2, ' \
1053
+ 'fillcolor="#1F3A5F", color="#142A45", fontcolor="#FFFFFF", fontsize=14'
1054
+ elsif node[:kind] == :job && job_failed.call(key)
1055
+ 'shape=box, class="prov-job prov-error", style="rounded,filled", ' \
1056
+ 'fillcolor="#FBE3E3", color="#C0392B", fontcolor="#8E2418"'
1057
+ elsif node[:kind] == :job
1058
+ 'shape=box, class="prov-job", style="rounded,filled", ' \
1059
+ 'fillcolor="#DCE9F7", color="#4A7EBB", fontcolor="#1F3A5F"'
1060
+ elsif society_label_pair(path)
1061
+ 'shape=note, class="prov-society", style=filled, ' \
1062
+ 'fillcolor="#F1F3F5", color="#9AA5B1", fontcolor="#5A6672"'
1063
+ elsif produced_keys.include?(key)
1064
+ 'shape=note, class="prov-chat", style=filled, ' \
1065
+ 'fillcolor="#FFF6DC", color="#C9A227", fontcolor="#5C5236"'
1066
+ else
1067
+ 'shape=note, class="prov-chat", style=filled, ' \
1068
+ 'fillcolor="#F1F3F5", color="#9AA5B1", fontcolor="#5A6672"'
1069
+ end
1070
+ attrs = attrs.sub(/class="([^"]*)"/) { %(class="#{$1} prov-overlap") } if overlap_keys.include?(key)
1071
+ format(' %s [%s, label=%s, tooltip=%s];',
1072
+ ids[key], attrs, JSON.generate(lines * "\n"), JSON.generate(path))
1073
+ end
1074
+
1075
+ # ---- Spine (spec S6): consecutive pairs of the time sequence.
1076
+ # A pair already joined by a delegates or produces edge reuses that
1077
+ # edge as the spine segment (constraint=true); every other pair gets
1078
+ # a synthetic class="timeline" edge. Any semantic edge not reused is
1079
+ # demoted to constraint=false, so the time axis stays authoritative:
1080
+ # each non-root node ends up with exactly one incoming constraint=true
1081
+ # edge and the chain rooted at the root reaches every node in order.
1082
+ delegates_of = {}
1083
+ produces_of = {}
1084
+ delegates.each { |edge| delegates_of[[edge[:from], edge[:to]]] = true }
1085
+ produces.each { |edge| produces_of[[edge[:from], edge[:to]]] = true }
1086
+ semantic = []
1087
+ delegates.each { |edge| semantic << {from: edge[:from], to: edge[:to], kind: :delegates} }
1088
+ produces.each { |edge| semantic << {from: edge[:from], to: edge[:to], kind: :produces} }
1089
+ continues.each { |edge| semantic << {from: edge[:from], to: edge[:to], kind: :continues} }
1090
+ log_edges.each { |edge| semantic << {from: edge[:from], to: edge[:to], kind: :log} }
1091
+ dependency_edges.each { |edge| semantic << {from: edge[:from], to: edge[:to], kind: :dependency} }
1092
+
1093
+ spine_reuse = {}
1094
+ sequence.each_cons(2) do |first, second|
1095
+ pair = [first, second]
1096
+ spine_reuse[pair] = :delegates if delegates_of.key?(pair)
1097
+ spine_reuse[pair] ||= :produces if produces_of.key?(pair)
1098
+ end
1099
+ spine_edges = sequence.each_cons(2).collect do |first, second|
1100
+ pair = [first, second]
1101
+ kind = spine_reuse[pair]
1102
+ {from: first, to: second, kind: kind || :synthetic}
1103
+ end
1104
+ reused_pairs = spine_edges.select { |edge| edge[:kind] != :synthetic }
1105
+ .collect { |edge| [edge[:from], edge[:to]] }.to_set
1106
+ side_edges = semantic.reject { |edge| reused_pairs.include?([edge[:from], edge[:to]]) }
1107
+
1108
+ # ---- Temporal clusters (spec S7): one cluster per continuation
1109
+ # chain IF AND ONLY IF its members (chain jobs + produced chats)
1110
+ # form a contiguous block of the sequence; society chats are never
1111
+ # enclosed (they interleave with jobs in time).
1112
+ timeline_cluster_blocks = []
1113
+ timeline_cluster_members = Set.new
1114
+ chain_members.sort_by { |name, _members| name }.each do |name, members|
1115
+ members = members.reject { |key| timeline_cluster_members.include?(key) || key == root_key }
1116
+ next if members.empty?
1117
+ indexes = members.collect { |key| sequence_index[key] }.compact.sort
1118
+ next if indexes.empty?
1119
+ contiguous = indexes.each_cons(2).all? { |a, b| b == a + 1 }
1120
+ next unless contiguous
1121
+ timeline_cluster_members.merge(members)
1122
+ suffix = name.gsub(/[^A-Za-z0-9]/, '_')
1123
+ timeline_cluster_blocks << [
1124
+ " subgraph cluster_#{suffix} {",
1125
+ " label=\"#{name} continuation chain\"; labeljust=l; fontsize=10; fontcolor=\"#1F3A5F\";",
1126
+ ' style="rounded,filled"; fillcolor="#F7F9FB"; color="#C7D0D9";',
1127
+ ' ' + members.collect { |key| ids[key] } * '; ' + ';',
1128
+ ' }'
1129
+ ] * "\n"
1130
+ end
1131
+
1132
+ # ---- Edges: spine first (constraint=true), then the semantic edges
1133
+ # transposed to TB (spec S5). Ports rotate with the layout: the flow
1134
+ # s/n pair becomes e/w, delegates keep their own left-margin face
1135
+ # (headport=w) and continues the right corridor (tailport=e
1136
+ # headport=w). Labels survive on continues arcs only.
1137
+ timeline_edge_lines = []
1138
+ spine_edges.each do |edge|
1139
+ case edge[:kind]
1140
+ when :synthetic
1141
+ timeline_edge_lines << format(' %s -> %s [color="#C7D0D9", penwidth=0.8, class="timeline", constraint=true];',
1142
+ ids[edge[:from]], ids[edge[:to]])
1143
+ when :delegates
1144
+ timeline_edge_lines << format(' %s -> %s [color="#1F3A5F", penwidth=1.6, class="delegated_result", headport=w, constraint=true];',
1145
+ ids[edge[:from]], ids[edge[:to]])
1146
+ when :produces
1147
+ timeline_edge_lines << format(' %s -> %s [color="#4A7EBB", penwidth=1.1, class="dependency", headport=w, constraint=true];',
1148
+ ids[edge[:from]], ids[edge[:to]])
1149
+ end
1150
+ end
1151
+ side_edges.each do |edge|
1152
+ case edge[:kind]
1153
+ when :delegates
1154
+ timeline_edge_lines << format(' %s -> %s [color="#1F3A5F", penwidth=1.6, class="delegated_result", headport=w, constraint=false];',
1155
+ ids[edge[:from]], ids[edge[:to]])
1156
+ when :produces
1157
+ timeline_edge_lines << format(' %s -> %s [color="#4A7EBB", penwidth=1.1, class="dependency", headport=w, constraint=false];',
1158
+ ids[edge[:from]], ids[edge[:to]])
1159
+ when :continues
1160
+ timeline_edge_lines << format(' %s -> %s [label="continues", color="#6E5AA8", fontcolor="#6E5AA8", ' \
1161
+ 'penwidth=1.3, constraint=false, tailport=e, headport=w];',
1162
+ ids[edge[:from]], ids[edge[:to]])
1163
+ when :dependency
1164
+ timeline_edge_lines << format(' %s -> %s [color="#8A93A0", penwidth=0.9, class="dependency", constraint=false];',
1165
+ ids[edge[:from]], ids[edge[:to]])
1166
+ when :log
1167
+ timeline_edge_lines << format(' %s -> %s [style=dashed, color="#B0B7C3", penwidth=0.9];',
1168
+ ids[edge[:from]], ids[edge[:to]])
1169
+ end
1170
+ end
1171
+
1172
+ timeline_lines = [
1173
+ 'digraph prov_timeline {',
1174
+ ' graph [rankdir=TB, splines="spline", bgcolor="white", pad=0.25, nodesep=0.35, ranksep=0.45, ' \
1175
+ 'fontname="Helvetica", fontsize=11];',
1176
+ ' node [shape=box, style=filled, fontname="Helvetica", fontsize=11, margin="0.14,0.09"];',
1177
+ ' edge [fontname="Helvetica", fontsize=9, fontcolor="#6B7280", arrowsize=0.8, color="#8A93A0"];',
1178
+ '',
1179
+ timeline_node_lines,
1180
+ '',
1181
+ timeline_cluster_blocks,
1182
+ '',
1183
+ " {rank=source; #{ids[sequence.first]};}",
1184
+ '',
1185
+ timeline_edge_lines,
1186
+ '}'
1187
+ ].flatten
1188
+ timeline_dot = timeline_lines * "\n"
1189
+
1190
+ timeline_extension = File.extname(timeline_file).sub(/^\./, '').downcase
1191
+ timeline_extension = 'svg' if timeline_extension.empty?
1192
+ if timeline_extension == 'dot'
1193
+ Open.write(timeline_file, timeline_dot)
1194
+ else
1195
+ raise ParameterException, "Unsupported timeline format: #{timeline_extension}" unless %w[svg png pdf].include?(timeline_extension)
1196
+ Tempfile.create(['scout-ai-provenance', '.dot']) do |file|
1197
+ file.write(timeline_dot)
1198
+ file.flush
1199
+ raise ScoutException, 'Graphviz dot failed' unless system('dot', "-T#{timeline_extension}", file.path, '-o', timeline_file.to_s)
1200
+ end
1201
+ end
1202
+ end
551
1203
  end
552
1204
 
553
1205
  # ------------------------------------------------------------------
@@ -558,7 +1210,7 @@ if evidence
558
1210
  return '' unless Array === address && address.any?
559
1211
  rest = address[1..-1]
560
1212
  base = address[0].nil? ? '?' : File.basename(address[0].to_s)
561
- if rest.length >= 3 && (rest[1] == :agent_meta || rest[1] == :meta)
1213
+ if rest.length >= 3 && rest[1] == :meta
562
1214
  "#{base}:#{rest[0]}[#{rest[1]},#{rest[2]}]"
563
1215
  else
564
1216
  "#{base}:#{rest[0]}"
@@ -672,6 +1324,19 @@ if evidence
672
1324
  end
673
1325
  end
674
1326
 
1327
+ # ------------------------------------------------------------------
1328
+ # Live workload (--live): the transient <base>.jobs sidecar
1329
+ # ------------------------------------------------------------------
1330
+ # The sidecar exists only while Workflow.produce blocks inside a tool round
1331
+ # of THIS chat's agent, so it is read opportunistically: absent file is a
1332
+ # non-event and prints nothing (silence, not an error). Entry
1333
+ # classification lives in the Chat utility layer (Chat.live_workload), so
1334
+ # the CLI only renders what the utility resolved.
1335
+ # --live: the unified live report (sidecar with dependency expansion, the
1336
+ # root agent's own view, and the society tree), minus everything the
1337
+ # forensic report above already captured. Silent when nothing is live.
1338
+ render_live_section.call(root) if live
1339
+
675
1340
  warnings.each do |warning|
676
1341
  error = warning[:error]
677
1342
  # Receipt problems are reported in detail by the receipt_warnings block