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
@@ -17,12 +17,24 @@ Examine the provenance of a chat or workflow job
17
17
  $ #{cmd} [<options>] <filename>
18
18
 
19
19
  -h--help Print this help
20
- -c--component Show per-component direct costs instead of aggregate totals
20
+ -c--component Show per-component direct costs (direct=) instead of subtree evidence closures (evidence=)
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
28
+
29
+ Default-tree numbers are evidence= subtree-deduplicated closures: they overlap
30
+ between nodes and are never per-part cost. Job nodes add delta= (direct tokens
31
+ of the persisted chat-typed result, the accounting delta). The root footer
32
+ always prints the authoritative deduplicated_total, in both modes; --component
33
+ relabels the node numbers direct=. cache= carries the cache-hit share of
34
+ prompt (cct/pt); the root footer adds fresh= (prompt not served from cache,
35
+ including cache_write) and cache_write= (Anthropic cache-write tokens).
36
+ Per-job delta= values sum to the root total on continuation chains but not on
37
+ general DAGs.
26
38
  EOF
27
39
  if options[:help]
28
40
  defined?(scout_usage) ? scout_usage : puts(SOPT.doc)
@@ -33,11 +45,19 @@ component = options.delete(:component)
33
45
  flow = options.delete(:flow)
34
46
  dot_file = options.delete(:dot)
35
47
  plot_file = options.delete(:plot)
48
+ timeline_file = options.delete(:timeline)
36
49
  long = options.delete(:long)
37
50
  evidence = options.delete(:evidence)
51
+ live = options.delete(:live)
38
52
  filename = ARGV.first
39
53
  raise MissingParameterException, :filename if filename.nil?
40
54
 
55
+ # One parse-once cache for the whole CLI run (see
56
+ # Chat.provenance_chat_load): the initial traversal, the token-event
57
+ # collector and this script's own node computations then share a single
58
+ # Chat object per resolved path.
59
+ Chat.open_provenance_run_cache
60
+
41
61
  # A persisted Step always has an info sidecar. A .files directory alone is NOT
42
62
  # evidence: saved agent chats carry one too. Explicitly loading the Step after
43
63
  # this evidence check avoids treating every readable chat as a job.
@@ -45,19 +65,30 @@ job_evidence = Open.exists?(filename + '.info')
45
65
  root_type = job_evidence ? :job : :chat
46
66
  root = root_type == :job ? Step.load(filename) : Path.setup(File.expand_path(filename))
47
67
  warnings = []
48
- records = Chat.traverse_provenance(
49
- root,
50
- root_type: root_type,
51
- on_error: lambda do |error, kind, object, relation, reference|
52
- warnings << {
53
- error: error,
54
- kind: kind,
55
- object: object,
56
- relation: relation,
57
- reference: reference
58
- }
59
- end
60
- ).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
61
92
 
62
93
  # ------------------------------------------------------------------
63
94
  # Build graph: nodes keyed by [kind, path], edges as {from, to, relation}
@@ -82,6 +113,116 @@ records.each do |kind, object, parent_kind, parent, relation, first_visit, _deta
82
113
  end
83
114
  root_key = Chat.provenance_key(root_type, root)
84
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
+
85
226
  # Adjacency: parent -> children, sorted for readability
86
227
  adjacency = Hash.new { |h, k| h[k] = [] }
87
228
  edges.each do |edge|
@@ -103,18 +244,36 @@ chat_cache = {}
103
244
  direct_tokens = lambda do |key|
104
245
  node = nodes[key]
105
246
  if node[:kind] == :chat
106
- chat = chat_cache[node[:path]] ||= Chat.load(node[:path])
247
+ chat = chat_cache[node[:path]] ||= Chat.provenance_chat_load(node[:path])
107
248
  Chat.token_totals([chat])
108
249
  else
109
250
  logs = edges.select { |e| e[:from] == key && e[:relation] == :log }
110
251
  .collect { |e| nodes[e[:to]][:path] }.uniq
111
- chats = logs.collect { |path| chat_cache[path] ||= Chat.load(path) }
252
+ chats = logs.collect { |path| chat_cache[path] ||= Chat.provenance_chat_load(path) }
112
253
  Chat.token_totals(chats)
113
254
  end
114
255
  rescue => error
115
256
  warnings << { error: error, kind: node[:kind], object: node[:object], relation: :tokens }
116
257
  Chat::TOKEN_KEYS.each_with_object({}) { |name, totals| totals[name.to_sym] = 0 }
117
258
  end
259
+ # Per-job accounting delta: the direct tokens of the job's persisted
260
+ # chat-typed result (Chat.job_result_chat_file). This is the
261
+ # receipt-defined accounting object - the new chat the job returned - so on a
262
+ # continuation chain the per-job deltas sum to the root deduplicated_total
263
+ # while every ancestor's evidence= closure stays cumulative. Jobs whose
264
+ # result is not chat-typed omit the field (nil, never zero).
265
+ delta_cache = {}
266
+ delta_tokens = lambda do |key|
267
+ return delta_cache[key] if delta_cache.key?(key)
268
+ node = nodes[key]
269
+ delta_cache[key] = if node[:kind] == :job
270
+ file = Chat.job_result_chat_file(node[:object])
271
+ file ? Chat.token_totals([chat_cache[Chat.provenance_path(:chat, file)] ||= Chat.provenance_chat_load(file)]) : nil
272
+ end
273
+ rescue => error
274
+ warnings << { error: error, kind: node[:kind], object: node[:object], relation: :delta }
275
+ delta_cache[key] = nil
276
+ end
118
277
 
119
278
  # ------------------------------------------------------------------
120
279
  # Receipt (agent_meta) evidence: delegated inference events embedded in
@@ -179,20 +338,16 @@ node_tokens = component ? direct_tokens : aggregate_tokens
179
338
  # Hidden nodes are skipped entirely — not printed and not traversed.
180
339
  # - result-relation chats: they duplicate the job node and create cycles
181
340
  # - top-level agent.chat log file: its cost is subsumed by the parent job.
182
- # ScoutCoder: DUAL-LAYOUT. The root copy of the agent conversation sits
183
- # directly under the files dir in BOTH layouts:
184
- # new <job>.files/agent.chat
185
- # legacy <job>.files/log/agent.chat
186
- # Any basename agent.chat whose parent is a `<something>.files` directory
187
- # (top level of the files dir) or the legacy `.../log` directory is such a
188
- # copy. NESTED society chats (agent.society/<agent>/<conv>/agent.chat,
189
- # log/society/<agent>/<conv>/agent.chat) are real independent inferences
190
- # 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.
191
347
  def top_level_agent_chat?(path)
192
348
  return false unless File.basename(path) == 'agent.chat'
193
349
  parent = File.dirname(path)
194
- parent.end_with?('/log') || parent.end_with?('/log/') ||
195
- parent.end_with?('.files')
350
+ parent.end_with?('.files')
196
351
  end
197
352
 
198
353
  def hidden_node?(node, relation)
@@ -204,21 +359,52 @@ end
204
359
  # ------------------------------------------------------------------
205
360
  # Formatting helpers
206
361
  # ------------------------------------------------------------------
207
- def token_str(tokens)
362
+ # `qualifier` names the total field after what it measures so a number can
363
+ # never be read as a different quantity: `evidence` (default tree; subtree
364
+ # deduplicated closure), `direct` (-c; per-component direct tokens),
365
+ # `deduplicated_total` (root footer; the authoritative cost). `events`
366
+ # appends the deduplicated event count where it is already computed (the
367
+ # footer), and `delta` inserts the job's result-chat delta right after it.
368
+ #
369
+ # Canonical field order, identical for node lines and the footer: qualifier
370
+ # total, [delta=], then the prompt axis `prompt= cache=<abs>@<rate> [fresh=]
371
+ # [cache_write=]`, then generation `cont= reason=`. `footer: true` adds the
372
+ # run-level economics (`fresh=`, `cache_write=`) that do not belong to a node
373
+ # label. The rate is always computed from RAW integer totals
374
+ # (`100.0 * cct / pt`): humanized values round at K/M boundaries and would
375
+ # corrupt boundary rates. `cache=` prints whenever pt is positive, including
376
+ # `cache=0@0.0%`; when pt is nil/0 the whole prompt axis is omitted (nothing
377
+ # to partition). A conflicting summed set can yield cct > pt; the raw ratio
378
+ # is then printed unclamped and the footer caveat line is the guard that
379
+ # labels such a figure best-effort.
380
+ def token_str(tokens, qualifier: nil, events: nil, delta: nil, footer: false)
208
381
  parts = []
209
- parts << "total=#{Misc.human_number(tokens[:tt])}" if tokens[:tt] && tokens[:tt].to_i > 0
210
- parts << "prompt=#{Misc.human_number(tokens[:pt])}" if tokens[:pt] && tokens[:pt].to_i > 0
382
+ if tokens[:tt] && tokens[:tt].to_i > 0
383
+ value = Misc.human_number(tokens[:tt])
384
+ value += " (#{events} events)" if events
385
+ parts << "#{qualifier || 'total'}=#{value}"
386
+ parts << "delta=#{Misc.human_number(delta[:tt])}" if delta && delta[:tt].to_i > 0
387
+ end
388
+ pt = tokens[:pt].to_i
389
+ if pt > 0
390
+ cct = tokens[:cct].to_i
391
+ parts << "prompt=#{Misc.human_number(pt)}"
392
+ parts << "cache=#{Misc.human_number(cct)}@#{format('%.1f', 100.0 * cct / pt)}%"
393
+ if footer
394
+ parts << "fresh=#{Misc.human_number(pt - cct)}"
395
+ parts << "cache_write=#{Misc.human_number(tokens[:cwt].to_i)}" if tokens[:cwt] && tokens[:cwt].to_i > 0
396
+ end
397
+ end
211
398
  parts << "cont=#{Misc.human_number(tokens[:ct])}" if tokens[:ct] && tokens[:ct].to_i > 0
212
- parts << "cache=#{Misc.human_number(tokens[:cct])}" if tokens[:cct] && tokens[:cct].to_i > 0
213
399
  parts << "reason=#{Misc.human_number(tokens[:rt])}" if tokens[:rt] && tokens[:rt].to_i > 0
214
400
  parts * ' '
215
401
  end
216
402
 
217
- def report_line(kind, label, tokens, offset: 0)
403
+ def report_line(kind, label, tokens, offset: 0, qualifier: nil, delta: nil, events: nil)
218
404
  color = kind == :job ? :yellow : :green
219
405
  parts = [' ' * (offset * 2)]
220
406
  parts << Log.color(color, kind.to_s)
221
- tok = token_str(tokens)
407
+ tok = token_str(tokens, qualifier: qualifier, events: events, delta: delta)
222
408
  parts << tok unless tok.empty?
223
409
  parts << Log.color(:blue, label.to_s) unless label.to_s.empty?
224
410
  parts * ' '
@@ -243,19 +429,26 @@ def node_label(node, parent_node = nil, root_key = nil, key = nil, long = false)
243
429
  workflow = job.info[:workflow] || job.info['workflow']
244
430
  task = job.info[:task_name] || job.info['task_name']
245
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
246
440
  workflow && task ? "#{workflow}/#{task} #{short_id}" : short_id
247
- elsif parent_node && parent_node[:kind] == :job && path.include?('.files/log/')
248
- # Log chat under a job: show path relative to the job's log directory.
249
- # Derive log dir from parent_node path (which is the realpath) to avoid
250
- # symlink-resolution mismatches between the Step object and node path.
251
- parent_log_dir = File.join(parent_node[:path] + ".files", "log")
252
- rel = Misc.path_relative_to(parent_log_dir, path)
253
- 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}"
254
447
  elsif parent_node && parent_node[:kind] == :job && path.include?(parent_node[:path] + '.files/')
255
- # ScoutCoder: DUAL-LAYOUT sibling of the legacy branch above. Log chat
256
- # under a job in the NEW layout (no log/ component): show the path
257
- # 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
258
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.
259
452
  parent_files_dir = parent_node[:path] + '.files'
260
453
  rel = Misc.path_relative_to(parent_files_dir, path)
261
454
  rel.nil? || rel.empty? ? File.basename(path) : rel
@@ -270,7 +463,7 @@ end
270
463
  # ------------------------------------------------------------------
271
464
  # Tree rendering (default mode)
272
465
  # ------------------------------------------------------------------
273
- unless flow || dot_file || plot_file
466
+ unless flow || dot_file || plot_file || timeline_file
274
467
  printed = Set.new
275
468
  print_tree = lambda do |key, offset, relation, parent_key|
276
469
  # Skip already-visited nodes entirely (no "(seen)" line)
@@ -279,14 +472,34 @@ unless flow || dot_file || plot_file
279
472
  node = nodes[key]
280
473
  parent_node = parent_key ? nodes[parent_key] : nil
281
474
 
282
- # Skip hidden nodes entirely — don't print, don't traverse children
283
- return if hidden_node?(node, relation)
475
+ # Hidden nodes (result chats duplicating a job, top-level agent.chat
476
+ # logs) are not printed, but PROJECTION ONLY: the walk still descends
477
+ # through them so their children are attributed to the current display
478
+ # parent. This is what makes delegated children of tree-hidden carrier
479
+ # chats visible without adding, removing or rewriting any traversal
480
+ # edge: the :agent_job/:job edges keep pointing at the carrier chat.
481
+ # - no "printed" slot is consumed, so offsets stay as if the carrier
482
+ # were not there
483
+ # - children keep their own incoming relation (delegated-job label)
484
+ # - the global `printed` set still dedups nodes discovered from
485
+ # several carriers (first visit wins)
486
+ if hidden_node?(node, relation)
487
+ (adjacency[key] || []).each do |edge|
488
+ print_tree.call(edge[:to], offset, edge[:relation], parent_key)
489
+ end
490
+ return
491
+ end
284
492
 
285
493
  printed << key
286
494
  label = node_label(node, parent_node, root_key, key, long)
287
495
  # A job reached through an agent_meta receipt is a delegated producer.
288
496
  label = "delegated-job #{label}" if node[:kind] == :job && relation == :agent_job
289
- puts report_line(node[:kind], label, node_tokens.call(key), offset: offset)
497
+ # Both modes: job nodes carry their accounting delta (in -c the
498
+ # direct=/delta= contrast on one line is the question the mode answers).
499
+ delta = node[:kind] == :job ? delta_tokens.call(key) : nil
500
+ puts report_line(node[:kind], label, node_tokens.call(key), offset: offset,
501
+ qualifier: component ? 'direct' : 'evidence',
502
+ delta: delta)
290
503
 
291
504
  # One compact annotation line for the delegated usage embedded in this
292
505
  # chat's own outputs; never one line per receipt.
@@ -309,6 +522,25 @@ unless flow || dot_file || plot_file
309
522
  end
310
523
  print_tree.call(root_key, 0, nil, nil)
311
524
 
525
+ # Root footer (BOTH modes): the one authoritative cost figure, always
526
+ # printed, so -c no longer lacks a global bound. It carries the run-level
527
+ # economics (deduplicated event count, fresh=, cache_write=) that do not
528
+ # belong to a node label. It reuses the root aggregate computed for the
529
+ # root node line, which IS the root :deduplicated_total (every deduplicated
530
+ # event once). Identity conflicts demote it to best-effort; this footer
531
+ # caveat is the single home of the non-authoritative warning in both modes
532
+ # (the -c scope block no longer repeats it).
533
+ conflicts = {}
534
+ root_totals = Chat.provenance_token_totals(root, warnings: receipt_warnings, conflicts: conflicts)
535
+ puts Log.color(:cyan, 'root ') +
536
+ token_str(root_totals, qualifier: 'deduplicated_total',
537
+ events: token_events_for.call.length, footer: true) + ' ' +
538
+ Log.color(:cyan, '(authoritative cost; per-node evidence=/direct= values overlap)')
539
+ unless conflicts[:authoritative]
540
+ puts Log.color(:red, 'unresolved identity conflicts: ') +
541
+ "#{conflicts[:events]} conflicting event(s); totals above are best-effort (canonical evidence only), not exact"
542
+ end
543
+
312
544
  # Component mode: make the evidence coverage behind the numbers explicit
313
545
  # once receipts are present; chats without receipts keep the previous output
314
546
  # exactly. These are COVERAGE figures, not additive cost categories:
@@ -316,8 +548,7 @@ unless flow || dot_file || plot_file
316
548
  # both a saved child log and a receipt. Only deduplicated_total is the
317
549
  # cost, and receipt_only is the disjoint delegated contribution.
318
550
  if component && has_receipt_evidence
319
- coverage = [[:deduplicated_total, 'total'],
320
- [:chat_evidence, 'events with saved chat/log evidence'],
551
+ coverage = [[:chat_evidence, 'events with saved chat/log evidence'],
321
552
  [:receipt_evidence, 'events inside agent_meta receipts (overlaps chat_evidence)'],
322
553
  [:receipt_only, 'receipt evidence with no saved chat/log']]
323
554
  coverage.each do |scope, note|
@@ -326,13 +557,6 @@ unless flow || dot_file || plot_file
326
557
  rendered = 'total=0' if rendered.empty?
327
558
  puts Log.color(:cyan, "evidence #{scope}:") + ' ' + rendered + ' ' + Log.color(:cyan, "(#{note})")
328
559
  end
329
-
330
- conflict_info = {}
331
- Chat.provenance_token_totals(root, warnings: [], conflicts: conflict_info)
332
- unless conflict_info[:authoritative]
333
- puts Log.color(:red, 'unresolved identity conflicts: ') +
334
- "#{conflict_info[:events]} conflicting event(s); totals above are best-effort (canonical evidence only), not exact"
335
- end
336
560
  end
337
561
  end
338
562
 
@@ -353,7 +577,7 @@ flow_edges = edges.collect do |edge|
353
577
  end
354
578
  end.uniq
355
579
 
356
- if flow || dot_file || plot_file
580
+ if flow || dot_file || plot_file || timeline_file
357
581
  # Determine visible nodes using same rules as tree mode.
358
582
  hidden_keys = Set.new
359
583
  nodes.each do |key, node|
@@ -413,31 +637,263 @@ if flow || dot_file || plot_file
413
637
  end
414
638
  end
415
639
 
416
- 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.
417
652
  ids = ordered_keys.each_with_index.to_h { |key, index| [key, "n#{index}"] }
418
- lines = [
419
- 'digraph scout_ai_provenance {',
420
- ' graph [rankdir=LR, bgcolor="white", pad=0.2, nodesep=0.35, ranksep=0.6];',
421
- ' node [fontname="Helvetica", fontsize=10];',
422
- ' edge [fontname="Helvetica", fontsize=8, arrowsize=0.7];'
423
- ]
424
- ordered_keys.each do |key|
425
- node = nodes[key]
426
- label = "#{node[:kind].to_s.capitalize}\n#{node_label(node, nil, nil, key, long)}\n#{short_number(node_tokens.call(key)[:tt])} tokens"
427
- shape = node[:kind] == :job ? 'box' : 'note'
428
- lines << %( #{ids[key]} [shape=#{shape}, style="rounded,filled", fillcolor="#f7f7f7", label=#{JSON.generate(label)}];)
429
- end
430
- styles = {
431
- result: 'color="#39804a", penwidth=1.5, label="result"',
432
- delegated_result: 'color="#8a6d3b", penwidth=1.2, label="delegated_result"',
433
- dependency: 'color="#333333", label="dependency"',
434
- log: 'color="#2864a5", style="dashed", label="log"'
435
- }
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 = []
436
674
  flow_edges.each do |edge|
437
- next unless visible_set.include?(edge[:from]) && visible_set.include?(edge[:to])
438
- 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?)
439
761
  end
440
- lines << '}'
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"
844
+ end
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
441
897
  dot = lines * "\n"
442
898
  Open.write(dot_file, dot) if dot_file
443
899
 
@@ -452,6 +908,298 @@ if flow || dot_file || plot_file
452
908
  end
453
909
  end
454
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
455
1203
  end
456
1204
 
457
1205
  # ------------------------------------------------------------------
@@ -462,7 +1210,7 @@ if evidence
462
1210
  return '' unless Array === address && address.any?
463
1211
  rest = address[1..-1]
464
1212
  base = address[0].nil? ? '?' : File.basename(address[0].to_s)
465
- if rest.length >= 3 && (rest[1] == :agent_meta || rest[1] == :meta)
1213
+ if rest.length >= 3 && rest[1] == :meta
466
1214
  "#{base}:#{rest[0]}[#{rest[1]},#{rest[2]}]"
467
1215
  else
468
1216
  "#{base}:#{rest[0]}"
@@ -576,6 +1324,19 @@ if evidence
576
1324
  end
577
1325
  end
578
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
+
579
1340
  warnings.each do |warning|
580
1341
  error = warning[:error]
581
1342
  # Receipt problems are reported in detail by the receipt_warnings block
@@ -600,3 +1361,7 @@ receipt_warnings.each do |warning|
600
1361
  Log.warn "agent_meta receipt: #{warning[:reason]} in #{warning[:source]} at #{location.inspect} call=#{warning[:call_id]}#{warning[:message] ? ' - ' + warning[:message] : ''}"
601
1362
  end
602
1363
  end
1364
+
1365
+ # End of the CLI run: drop the parse-once cache so a following run in the
1366
+ # same process (tests, embedded use) re-parses freshly.
1367
+ Chat.close_provenance_run_cache