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
@@ -3,222 +3,157 @@ require 'time'
3
3
 
4
4
  module Chat
5
5
  PROVENANCE_RELATIONS = %i[job dependency log result agent_job].freeze
6
+ DIRECT_LOG_CHAT_GLOBS = ['*.chat', '*.society/**/*.chat'].freeze
7
+ PROVENANCE_CACHE_KEY = :scout_ai_provenance_run_cache
8
+
9
+ # A cache lives for one top-level operation only. Nested operations reuse it.
10
+ def self.with_provenance_run_cache
11
+ previous = Thread.current[PROVENANCE_CACHE_KEY]
12
+ Thread.current[PROVENANCE_CACHE_KEY] ||= {}
13
+ yield
14
+ ensure
15
+ Thread.current[PROVENANCE_CACHE_KEY] = previous
16
+ end
6
17
 
7
- # ScoutCoder: DUAL-LAYOUT note. Two on-disk layouts must be globbed for a
8
- # job's own chat logs and for a saved chat's .files sidecar:
9
- #
10
- # new <x>.files/<name>.chat (agent.chat, worker.chat, ...)
11
- # new <x>.files/<name>.society/**/*.chat (society tree; nested
12
- # societies keep the plain 'society' basename deeper down)
13
- # legacy <x>.files/log/**/*.chat (written by older
14
- # scout-ai; read-only compatibility, never migrated)
15
- #
16
- # Exactly these three families may be swept: resets/, other *.files
17
- # subdirectories and second-order .files trees stay invisible. Files matched
18
- # by more than one pattern are deduplicated and results are sorted so the
19
- # traversal order is deterministic.
20
- DIRECT_LOG_CHAT_GLOBS = ['*.chat', '*.society/**/*.chat', 'log/**/*.chat'].freeze
21
-
22
- # Glob DIRECT_LOG_CHAT_GLOBS under `files_dir` and return a de-duplicated,
23
- # sorted list of existing chat files (Path objects). Both new and legacy
24
- # layouts are returned together; callers that must exclude the root copy of
25
- # the root conversation (Chat.direct_chat_sidecar_files) filter afterwards.
26
- def self.direct_log_chat_glob(files_dir)
27
- files_dir = files_dir.to_s
28
- return [] unless File.directory?(files_dir)
29
- DIRECT_LOG_CHAT_GLOBS
30
- .flat_map { |pattern| Dir.glob(File.join(files_dir, pattern)) }
31
- .collect { |file| File.expand_path(file) }
18
+ # Prefer the block form (with_provenance_run_cache) whenever a scope is
19
+ # expressible as a block. The manual pair exists for callers that must
20
+ # hold the cache across separate operations, like the `llm prov` CLI,
21
+ # which opens it once and traverses several roots under it.
22
+ def self.open_provenance_run_cache
23
+ Thread.current[PROVENANCE_CACHE_KEY] ||= {}
24
+ end
25
+
26
+ def self.close_provenance_run_cache
27
+ Thread.current[PROVENANCE_CACHE_KEY] = nil
28
+ end
29
+
30
+ def self.provenance_path(kind, object)
31
+ path = File.expand_path(kind.to_sym == :job ? object.path.to_s : object.to_s)
32
+ File.realpath(path)
33
+ rescue SystemCallError
34
+ path
35
+ end
36
+
37
+ def self.provenance_key(kind, object)
38
+ [kind.to_sym, provenance_path(kind, object)]
39
+ end
40
+
41
+ def self.provenance_chat_load(path)
42
+ cache = Thread.current[PROVENANCE_CACHE_KEY]
43
+ return Chat.load(path) unless cache
44
+ cache[provenance_path(:chat, path)] ||= Chat.load(path)
45
+ end
46
+
47
+ def self.direct_log_chat_files(files_dir)
48
+ return [] unless File.directory?(files_dir.to_s)
49
+
50
+ DIRECT_LOG_CHAT_GLOBS.flat_map do |pattern|
51
+ Dir.glob(File.join(files_dir.to_s, pattern))
52
+ end.map { |file| File.expand_path(file) }
32
53
  .select { |file| File.file?(file) }
33
- .uniq
34
- .sort
35
- .collect { |file| Path.setup(file) }
54
+ .uniq.sort.map { |file| Path.setup(file) }
36
55
  end
37
56
 
38
- # ScoutCoder: DUAL-LAYOUT globbing (see DIRECT_LOG_CHAT_GLOBS): a job's own
39
- # chat logs live at <job>.files/<name>.chat (new), under
40
- # <job>.files/<name>.society/** (new society tree) or under the legacy
41
- # <job>.files/log/** (written by older scout-ai; read-only compatibility,
42
- # never migrated). This method is deliberately not recursive; recursion
43
- # belongs to traverse_provenance.
44
57
  def self.direct_job_chat_files(job)
45
58
  job = Step.load(job) unless Step === job
46
- direct_log_chat_glob(job.files_dir)
59
+ direct_log_chat_files(job.files_dir)
47
60
  end
48
61
 
49
- # Return only chat logs owned by this persisted chat's .files sidecar. The
50
- # save mechanism writes saved agent conversations into the chat's .files dir
51
- # exactly like a job does, so a chat with a sidecar is scanned the same way a
52
- # job is. This method is deliberately not recursive; recursion belongs to
53
- # traverse_provenance.
54
- #
55
- # ScoutCoder: DUAL-LAYOUT globbing (see DIRECT_LOG_CHAT_GLOBS) plus the
56
- # root-copy exclusion. The save mechanism writes a full copy of the ROOT
57
- # conversation at the TOP LEVEL of the files dir in BOTH layouts:
58
- #
59
- # new <path>.files/<name>.chat (agent.chat, worker.chat, ...)
60
- # legacy <path>.files/log/agent.chat
61
- #
62
- # Those top-level copies must be excluded here or the chat would get a
63
- # self-edge duplicating the root node. Note the asymmetry with
64
- # direct_job_chat_files: a JOB's own top-level agent.chat IS traversed
65
- # (renderers hide it), a CHAT's root copy is NOT. Only TOP-LEVEL *.chat
66
- # files are excluded: society chats under <name>.society/ (new) and under
67
- # log/society/ (legacy) are independent conversations and are included.
62
+ # A chat's top-level .files/*.chat transcript is included unless it is a
63
+ # byte-identical copy of the root chat. Society descendants are independent.
68
64
  def self.direct_chat_sidecar_files(path)
69
65
  files_dir = path.to_s + '.files'
70
66
  return [] unless File.directory?(files_dir)
71
- top_level = Dir.glob(File.join(files_dir, '*.chat')).collect { |file| File.expand_path(file) }
72
- root_copy_legacy = File.expand_path(File.join(files_dir, 'log', 'agent.chat'))
73
- direct_log_chat_glob(files_dir).reject do |file|
74
- top_level.include?(file.to_s) || file.to_s == root_copy_legacy
67
+
68
+ top_level = Dir.glob(File.join(files_dir, '*.chat')).map { |f| File.expand_path(f) }.to_set
69
+ root_path = File.expand_path(path.to_s)
70
+ root_content = File.file?(root_path) ? Open.read(root_path) : nil
71
+
72
+ direct_log_chat_files(files_dir).reject do |file|
73
+ top_level.include?(file.to_s) && root_content &&
74
+ File.file?(file.to_s) && Open.read(file.to_s) == root_content
75
75
  end
76
76
  end
77
77
 
78
- # Return the persisted result as a chat file when the Step result type is
79
- # chat. A job and its result chat may have the same path; traversal identities
80
- # therefore always include the node kind.
81
78
  def self.job_result_chat_file(job)
82
79
  job = Step.load(job) unless Step === job
83
- return nil unless job.type.to_s == 'chat' && File.file?(job.path.to_s)
80
+ return unless job.type.to_s == 'chat' && File.file?(job.path.to_s)
84
81
  Path.setup(File.expand_path(job.path.to_s))
85
82
  end
86
83
 
87
- def self.provenance_path(kind, object)
88
- path = File.expand_path(kind.to_sym == :job ? object.path.to_s : object.to_s)
89
- File.realpath(path)
90
- rescue SystemCallError
91
- path
92
- end
93
-
94
- def self.provenance_key(kind, object)
95
- [kind.to_sym, provenance_path(kind, object)]
84
+ def self.job_reference_fallback_bases
85
+ ['~/.rbbt/var/jobs', Scout.var.jobs.find.to_s].map { |base| File.expand_path(base) }
96
86
  end
97
87
 
98
- def self.provenance_error(on_error, error, kind, object, relation, reference)
99
- raise error unless on_error
100
- on_error.call(error, kind, object, relation, reference)
88
+ def self.job_reference_candidate?(path)
89
+ File.exist?(path.to_s) || File.exist?(path.to_s + '.info')
101
90
  end
102
91
 
103
- # Resolve a job reference from a chat meta message into a Step. References
104
- # like "Planned/ask/Default_abc.chat" are relative workflow paths. Step.load
105
- # may resolve them to a Scout-specific directory that does not contain the
106
- # actual job data, so we fall back to checking Rbbt.var.jobs and Scout.var.jobs.
107
92
  def self.load_job_reference(reference)
108
93
  return reference if Step === reference
109
- ref_str = reference.to_s
110
-
111
- step = Step.load(ref_str)
112
- return step if File.exist?(step.path.to_s) || File.exist?(step.path.to_s + '.info')
113
-
114
- # Step.load resolves relative workflow paths (e.g. Planned/ask/Default_xyz.chat)
115
- # via Path.find, which may point to a directory that does not contain the
116
- # actual job data (e.g. ~/.scout/ instead of ~/.rbbt/var/jobs/). Try the
117
- # standard Rbbt workflow storage location as a fallback.
118
- rbbt_candidate = File.expand_path(File.join('~/.rbbt/var/jobs', ref_str))
119
- return Step.load(rbbt_candidate) if File.exist?(rbbt_candidate) || File.exist?(rbbt_candidate + '.info')
94
+ ref = reference.to_s
95
+ step = Step.load(ref)
96
+ return step if job_reference_candidate?(step.path)
120
97
 
98
+ job_reference_fallback_bases.each do |base|
99
+ candidate = File.join(base, ref)
100
+ return Step.load(candidate) if job_reference_candidate?(candidate)
101
+ end
121
102
  step
122
103
  end
123
104
 
124
- # Resolve one job reference into a usable Step. Returns [step, nil] when the
125
- # job data is loadable (path or .info sidecar exists) and [nil, step] when the
126
- # reference resolves to a directory without job data, keeping the would-be
127
- # step for diagnostics. Used by the :agent_job relation so unresolved
128
- # receipt references are reported instead of enqueued.
129
105
  def self.resolve_job_reference(reference)
130
106
  step = load_job_reference(reference)
131
- path = step.path.to_s
132
- if File.exist?(path) || File.exist?(path + '.info')
133
- [step, nil]
134
- else
135
- [nil, step]
136
- end
107
+ job_reference_candidate?(step.path) ? [step, nil] : [nil, step]
108
+ end
109
+
110
+ def self.provenance_error(on_error, error, kind, object, relation, reference)
111
+ raise error unless on_error
112
+ on_error.call(error, kind, object, relation, reference)
137
113
  end
138
114
 
139
- # Diagnostics for agent_meta receipt problems found while expanding one chat
140
- # node: malformed receipts collected by Chat.agent_meta_job_references.
141
- # Provenance is only ever extracted from parsed function_call_output JSON
142
- # Hashes carrying an explicit receipt key (current `meta`, legacy
143
- # `agent_meta`); raw output text is never
144
- # inspected, so output content that merely mentions "agent_meta" cannot
145
- # produce a warning. Each malformed record becomes one Chat.provenance_error
146
- # call with relation :agent_job and kind/object :chat + the chat path, so
147
- # strict mode (no on_error) raises ScoutException while warning mode keeps
148
- # going. Returns the valid job references so the caller can enqueue them
149
- # afterwards.
150
115
  def self.report_agent_meta_problems(chat, object, on_error = nil)
151
116
  warnings = []
152
117
  references = agent_meta_job_references(chat, source: object, warnings: warnings)
153
-
154
118
  warnings.each do |warning|
155
119
  error = ScoutException.new(
156
120
  agent_meta_error_message(warning[:reason],
157
- chat_path: object.to_s,
158
- output_address: warning[:output_address],
159
- call_id: warning[:call_id],
160
- tool_name: warning[:tool_name],
161
- reference: warning[:reference] || warning[:raw_entry])
121
+ chat_path: object.to_s, output_address: warning[:output_address],
122
+ call_id: warning[:call_id], tool_name: warning[:tool_name],
123
+ reference: warning[:reference] || warning[:raw_entry])
162
124
  )
163
- reference = agent_meta_error_reference(reason: warning[:reason],
164
- source: warning[:source] || object.to_s,
165
- output_address: warning[:output_address],
166
- evidence_address: warning[:evidence_address],
167
- call_id: warning[:call_id],
168
- tool_name: warning[:tool_name],
169
- agent_meta_index: warning[:agent_meta_index],
170
- raw_entry: warning[:raw_entry],
171
- reference: warning[:reference])
172
- provenance_error(on_error, error, :chat, object, :agent_job, reference)
125
+ detail = agent_meta_error_reference(
126
+ reason: warning[:reason], source: warning[:source] || object.to_s,
127
+ output_address: warning[:output_address], evidence_address: warning[:evidence_address],
128
+ call_id: warning[:call_id], tool_name: warning[:tool_name],
129
+ agent_meta_index: warning[:agent_meta_index], raw_entry: warning[:raw_entry],
130
+ reference: warning[:reference])
131
+ provenance_error(on_error, error, :chat, object, :agent_job, detail)
173
132
  end
174
-
175
133
  references
176
134
  end
177
135
 
178
- # Traverse the heterogeneous provenance graph using native Path and Step
179
- # values. The block receives:
180
- #
181
- # kind, object, parent_kind, parent, relation, first_visit, detail
182
- #
183
- # `kind` is :chat or :job. Chat objects are persisted file Paths; jobs are
184
- # Steps. The root has nil parent/relation. Every structural edge is yielded,
185
- # including an edge to a node visited through another branch; first_visit is
186
- # false in that case and the node is not expanded again.
187
- #
188
- # `detail` is nil for every ordinary edge. For an :agent_job edge it is the
189
- # agent_meta receipt record (Chat.agent_meta_job_references entry) that
190
- # produced the edge, so the originating function output address, receipt
191
- # address, call id and tool name stay auditable without re-parsing the parent
192
- # chat. Blocks accepting only the first six arguments keep working; the
193
- # trailing detail is only passed when the block can receive it (or accepts
194
- # any number of arguments).
195
- #
196
- # Relations describe root-outward discovery, not diagram arrow direction:
197
- # chat -> producer job (:job), chat -> delegated-agent producer job
198
- # (:agent_job, from agent_meta receipts), job -> dependency (:dependency),
199
- # job -> log chat (:log), job -> result chat (:result), and chat -> log chat
200
- # of its own .files sidecar (:log, saved agent conversations, excluding the
201
- # root copy at <path>.files/log/agent.chat).
202
- #
203
- # Imported and continued chats are a chat-compilation concern, not a
204
- # provenance concern. They are resolved during Chat.parse and their content
205
- # is already inlined in the persisted chat file. Provenance traversal
206
- # therefore never follows import, continue, or last references.
136
+ # ADVANCED entry point: breadth-first graph traversal for callers that
137
+ # need manual control (streaming edges, custom first-visit handling).
138
+ # Prefer provenance_graph (single-node index) or provenance_closure
139
+ # (recursive closure) for inspection. Every edge is yielded, including
140
+ # edges to previously visited nodes; only first visits expand. Chat and
141
+ # job identities remain distinct even when a chat-producing job and its
142
+ # result share a path.
207
143
  def self.traverse_provenance(root, root_type: nil, follow: :all, on_error: nil, &block)
208
144
  return enum_for(__method__, root, root_type: root_type, follow: follow, on_error: on_error) unless block
209
- # Lambda blocks have strict arity; keep six-argument callbacks compatible
210
- # by only yielding the trailing detail when the block can receive it.
211
- detail_arity = lambda do
212
- return true if block.arity == -1
213
- block.arity >= 7
145
+ unless Thread.current[PROVENANCE_CACHE_KEY]
146
+ return with_provenance_run_cache do
147
+ traverse_provenance(root, root_type: root_type, follow: follow, on_error: on_error, &block)
148
+ end
214
149
  end
215
150
 
216
- relations = follow == :all ? PROVENANCE_RELATIONS : Array(follow).collect(&:to_sym)
151
+ relations = follow == :all ? PROVENANCE_RELATIONS : Array(follow).map(&:to_sym).uniq
217
152
  unknown = relations - PROVENANCE_RELATIONS
218
- raise ParameterException, "Unknown provenance relations: #{unknown * ', '}" if unknown.any?
153
+ raise ParameterException, "Unknown provenance relations: #{unknown.join(', ')}" unless unknown.empty?
219
154
 
220
- root_kind = root_type && root_type.to_sym
221
- root_kind ||= Step === root ? :job : :chat
155
+ root_kind = (root_type || (Step === root ? :job : :chat)).to_sym
156
+ raise ParameterException, "Unknown provenance root type: #{root_kind}" unless %i[chat job].include?(root_kind)
222
157
  root_object = if root_kind == :job
223
158
  Step === root ? root : Step.load(root)
224
159
  else
@@ -227,30 +162,30 @@ module Chat
227
162
  Path.setup(path)
228
163
  end
229
164
 
230
- queue = [[root_kind, root_object, nil, nil, nil]]
165
+ queue = [[root_kind, root_object, nil, nil, nil, nil]]
231
166
  seen = Set.new
167
+ cursor = 0
168
+ wants_detail = block.arity == -1 || block.arity >= 7 ||
169
+ block.parameters.any? { |kind, _name| kind == :rest }
232
170
 
233
- until queue.empty?
234
- kind, object, parent_kind, parent, relation, detail = queue.shift
171
+ while cursor < queue.length
172
+ kind, object, parent_kind, parent, relation, detail = queue[cursor]
173
+ cursor += 1
235
174
  key = provenance_key(kind, object)
236
- first_visit = !seen.include?(key)
237
- if detail_arity.call
238
- block.call(kind, object, parent_kind, parent, relation, first_visit, detail)
239
- else
240
- block.call(kind, object, parent_kind, parent, relation, first_visit)
241
- end
242
- next unless first_visit
175
+ first = !seen.include?(key)
176
+ args = [kind, object, parent_kind, parent, relation, first]
177
+ args << detail if wants_detail
178
+ block.call(*args)
179
+ next unless first
243
180
  seen << key
244
181
 
245
182
  begin
246
183
  if kind == :chat
247
- chat = Chat.load(object)
248
-
184
+ chat = provenance_chat_load(object)
249
185
  if relations.include?(:job)
250
186
  chat.jobs.each do |reference|
251
187
  begin
252
- job = load_job_reference(reference)
253
- queue << [:job, job, :chat, object, :job]
188
+ queue << [:job, load_job_reference(reference), :chat, object, :job, nil]
254
189
  rescue StandardError => error
255
190
  provenance_error(on_error, error, :chat, object, :job, reference)
256
191
  end
@@ -258,518 +193,309 @@ module Chat
258
193
  end
259
194
 
260
195
  if relations.include?(:agent_job)
261
- # Malformed receipts are diagnostics, never provenance; they are
262
- # reported through provenance_error and skipped.
263
- references = begin
264
- report_agent_meta_problems(chat, object, on_error)
265
- rescue StandardError => error
266
- provenance_error(on_error, error, :chat, object, :agent_job, object)
267
- []
268
- end
269
-
270
- references.each do |record|
196
+ records = begin
197
+ report_agent_meta_problems(chat, object, on_error)
198
+ rescue StandardError => error
199
+ provenance_error(on_error, error, :chat, object, :agent_job, object)
200
+ []
201
+ end
202
+ records.each do |record|
271
203
  reference = record[:job]
272
204
  begin
273
- job, _unresolved = resolve_job_reference(reference)
205
+ job, = resolve_job_reference(reference)
274
206
  if job
275
- # The receipt record travels with the edge as its detail so
276
- # the traversal keeps the originating output address, call
277
- # id and receipt index.
278
207
  queue << [:job, job, :chat, object, :agent_job, record]
279
208
  else
280
- error = ScoutException.new(
281
- agent_meta_error_message(:unresolved_job_reference,
282
- chat_path: object.to_s,
283
- output_address: record[:output_address],
284
- call_id: record[:call_id],
285
- tool_name: record[:tool_name],
286
- reference: reference)
287
- )
288
- provenance_error(on_error, error, :chat, object, :agent_job,
289
- agent_meta_error_reference(reason: :unresolved_job_reference,
290
- source: object.to_s,
291
- output_address: record[:output_address],
292
- evidence_address: record[:evidence_address],
293
- call_id: record[:call_id],
294
- tool_name: record[:tool_name],
295
- reference: reference))
209
+ error = ScoutException.new(agent_meta_error_message(
210
+ :unresolved_job_reference, chat_path: object.to_s,
211
+ output_address: record[:output_address], call_id: record[:call_id],
212
+ tool_name: record[:tool_name], reference: reference))
213
+ detail = agent_meta_error_reference(
214
+ reason: :unresolved_job_reference, source: object.to_s,
215
+ output_address: record[:output_address], evidence_address: record[:evidence_address],
216
+ call_id: record[:call_id], tool_name: record[:tool_name], reference: reference)
217
+ provenance_error(on_error, error, :chat, object, :agent_job, detail)
296
218
  end
297
219
  rescue StandardError => error
298
- provenance_error(on_error, error, :chat, object, :agent_job,
299
- agent_meta_error_reference(reason: :unresolved_job_reference,
300
- source: object.to_s,
301
- reference: reference,
302
- call_id: record[:call_id],
303
- tool_name: record[:tool_name]))
220
+ detail = agent_meta_error_reference(
221
+ reason: :unresolved_job_reference, source: object.to_s,
222
+ reference: reference, call_id: record[:call_id], tool_name: record[:tool_name])
223
+ provenance_error(on_error, error, :chat, object, :agent_job, detail)
304
224
  end
305
225
  end
306
226
  end
307
227
 
308
228
  if relations.include?(:log)
309
- # A saved chat owns its .files sidecar logs (society
310
- # conversations) just like a job owns its job logs.
311
229
  direct_chat_sidecar_files(object).each do |file|
312
- queue << [:chat, file, :chat, object, :log]
230
+ queue << [:chat, file, :chat, object, :log, nil]
313
231
  end
314
232
  end
315
233
  else
316
234
  if relations.include?(:dependency)
317
235
  object.dependencies.each do |dependency|
318
- queue << [:job, dependency, :job, object, :dependency]
236
+ queue << [:job, dependency, :job, object, :dependency, nil]
319
237
  end
320
238
  end
321
-
322
239
  if relations.include?(:log)
323
240
  direct_job_chat_files(object).each do |file|
324
- queue << [:chat, file, :job, object, :log]
241
+ queue << [:chat, file, :job, object, :log, nil]
325
242
  end
326
243
  end
327
-
328
244
  if relations.include?(:result) && (file = job_result_chat_file(object))
329
- queue << [:chat, file, :job, object, :result]
245
+ queue << [:chat, file, :job, object, :result, nil]
330
246
  end
331
247
  end
332
248
  rescue StandardError => error
333
249
  provenance_error(on_error, error, kind, object, relation, object)
334
250
  end
335
251
  end
336
-
337
252
  nil
338
253
  end
339
254
 
340
- # Flat structural edges suitable for JSON reports and renderers. Objects are
341
- # intentionally retained as native values; presentation code can shorten or
342
- # serialize paths as needed.
255
+ # COMPACT INDEX entry point: the immediate provenance of ONE chat or job
256
+ # as lightweight data (strings, symbols, integers, arrays, hashes).
343
257
  #
344
- # `:agent_job` edges carry the agent_meta receipt record that produced them
345
- # under `detail:` (call id, tool name, output address, receipt address, job
346
- # reference). Two distinct receipts pointing at the same job therefore remain
347
- # two distinguishable edges instead of collapsing into one; ordinary edges
348
- # keep `detail: nil`.
349
- def self.provenance_edges(root, **options)
350
- edges = []
351
- traverse_provenance(root, **options) do |kind, object, parent_kind, parent, relation, _first, detail|
352
- next unless parent
353
- edge = {
354
- from_kind: parent_kind,
355
- from: parent,
356
- relation: relation,
357
- to_kind: kind,
358
- to: object,
359
- detail: detail
360
- }
361
- same_edge = lambda do |other|
362
- other[:relation] == relation &&
363
- provenance_key(other[:from_kind], other[:from]) == provenance_key(parent_kind, parent) &&
364
- provenance_key(other[:to_kind], other[:to]) == provenance_key(kind, object) &&
365
- (relation != :agent_job ||
366
- (detail.nil? && other[:detail].nil?) ||
367
- (detail && other[:detail] && detail[:evidence_address] == other[:detail][:evidence_address]))
368
- end
369
- edges << edge unless edges.any?(&same_edge)
370
- end
371
- edges
372
- end
373
-
374
- def self.provenance_chat_files(root, **options)
375
- files = []
376
- traverse_provenance(root, **options) do |kind, object, _pk, _parent, _relation, first|
377
- files << provenance_path(kind, object) if first && kind == :chat
378
- end
379
- files
380
- end
381
-
382
- def self.provenance_jobs(root, **options)
383
- jobs = []
384
- traverse_provenance(root, **options) do |kind, object, _pk, _parent, _relation, first|
385
- jobs << object if first && kind == :job
258
+ # Chat.provenance_graph(chat_file) # =>
259
+ # { type: :chat,
260
+ # chats: { 3 => 'Planned/work/Default_agdfg' },
261
+ # dependencies: [],
262
+ # delegation: { 5 => 'Workspace#default' },
263
+ # live: ['<abs>/session.chat.files/agent.chat'],
264
+ # warnings: [] }
265
+ #
266
+ # `chats` maps persisted message indexes (zero-based array positions) to
267
+ # RESOLVED canonical absolute job paths, from BOTH a standalone
268
+ # `meta: job=` message and a job reference lifted from an agent_meta
269
+ # receipt inside a function_call_output envelope (anchored at the OUTER
270
+ # output message index). `dependencies` is the job's direct
271
+ # Step#dependencies canonical paths, declared order, chat roots always
272
+ # empty. Both are directly usable with Step.load; short metadata
273
+ # spellings and short_path values are never returned. `delegation` maps the
274
+ # index of an `ask` tool call message to '<agent>#<conversation>'. `live`
275
+ # lists supplementary sidecar chat paths (including a byte-identical
276
+ # top-level copy); these are mutable work in flight, NOT authoritative
277
+ # provenance nodes: nothing in them is loaded or followed here. Callers
278
+ # recurse by feeding any returned reference back in as the next root.
279
+ # There is no `follow` option and no recursion: one node per call.
280
+ def self.provenance_graph(root, root_type: nil, on_error: :collect)
281
+ warnings = []
282
+ report = lambda do |error, kind, object, relation, reference|
283
+ warnings << provenance_warning(error, kind, object, relation, reference)
386
284
  end
387
- jobs
388
- end
389
-
390
- # Compatibility collector for the former chat-to-chat provenance Hash. New
391
- # code should use traverse_provenance or provenance_edges, which retain job
392
- # nodes and relation types.
393
- def self.provenance(chat_file, prov = {})
394
- traverse_provenance(chat_file) do |kind, object, parent_kind, parent, _relation, _first|
395
- next unless parent && kind == :chat
396
- parent_path = provenance_path(parent_kind, parent)
397
- prov[parent_path] ||= []
398
- path = provenance_path(kind, object)
399
- prov[parent_path] << path unless prov[parent_path].include?(path)
285
+ callback = on_error == :raise ? nil : (report if on_error == :collect)
286
+ callback = lambda do |*args|
287
+ report.call(*args)
288
+ on_error.call(*args)
289
+ end if callback.nil? && on_error.respond_to?(:call)
290
+
291
+ root_kind = (root_type || (Step === root ? :job : :chat)).to_sym
292
+ raise ParameterException, "Unknown provenance root type: #{root_kind}" unless %i[chat job].include?(root_kind)
293
+ job = nil
294
+ chat_path = nil
295
+ if root_kind == :job
296
+ job = Step === root ? root : Step.load(root)
297
+ else
298
+ chat_path = File.expand_path(root.to_s)
299
+ raise ParameterException, "Chat not found: #{root}" unless File.file?(chat_path)
400
300
  end
401
- prov
402
- end
403
-
404
- # ------------------------------------------------------------------
405
- # Provenance-aware token accounting
406
- # ------------------------------------------------------------------
407
-
408
- # Canonical-evidence rule for grouped token events, applied in this order:
409
- #
410
- # 1. prefer :chat_meta evidence over :agent_meta evidence (a saved child
411
- # log chat is the richer, primary representation of the same request);
412
- # 2. within the same origin, the first evidence in discovery order
413
- # (provenance_chat_files order, then message index, then receipt
414
- # index).
415
- #
416
- # Event tokens always come from the canonical evidence only. Duplicate
417
- # evidence records are retained (never summed), so a total can always be
418
- # explained from the evidence list.
419
301
 
420
- # One event Hash per deduplicated direct inference event reachable from
421
- # `root`. A `job=` projection meta is never a token event, and only
422
- # evidence carrying at least one TOKEN_KEYS field becomes an event.
423
- #
424
- # Warning routing: when the caller supplies a `warnings` Array, two kinds of
425
- # problems are reported into it instead of raising:
426
- # * traversal-stage agent_meta problems (malformed receipts and unresolved
427
- # job references) arrive as the agent_meta_error_reference Hash plus
428
- # `message:`; the traversal keeps going so one bad receipt never hides
429
- # the rest of the provenance;
430
- # * identity_conflict records (see below).
431
- # Unrelated traversal errors keep strict semantics: they raise, both with and
432
- # without a warnings Array. Without the Array, agent_meta problems raise
433
- # exactly like Chat.traverse_provenance strict mode.
434
- #
435
- # Identity conflicts never raise here; pass `strict: true` to make them
436
- # raise instead of being reported (see below).
437
- #
438
- # Event shape:
439
- #
440
- # {
441
- # inference_id: <String or nil>,
442
- # identity: <the Array used for grouping, e.g. [:inference_id, "w1"]>,
443
- # deduplication: :inference_id | :provider_response_id |
444
- # :legacy_lineage | :receipt_unresolved,
445
- # meta: <canonical parsed meta>,
446
- # tokens: {pt:, ct:, tt:, cct:, cwt:, rt:} (symbols, zero-filled,
447
- # canonical evidence only),
448
- # evidence: [
449
- # {origin: :chat_meta, source:, meta_address:, meta:, call_id: nil,
450
- # tool_name: nil},
451
- # {origin: :agent_meta, source:, evidence_address:, output_address:,
452
- # agent_meta_index:, call_id:, tool_name:, meta:}
453
- # ],
454
- # conflict: true|false,
455
- # incomplete_evidence: true|false
456
- # }
457
- #
458
- # `evidence` holds EVERY persisted location of the event (the same
459
- # inference copied into several saved chats/logs appears once per chat plus
460
- # once per receipt). Only the canonical evidence supplies `meta` and
461
- # `tokens`.
462
- #
463
- # Identity (grouping) rules, in priority order:
464
- #
465
- # * meta[:inference_id] -> [:inference_id, id]
466
- # * meta[:provider_response_id] otherwise -> [:provider_response_id, id]
467
- # * chat-side legacy (neither) -> [:lineage, lineage_id], the
468
- # existing global lineage dedup of Chat.trace_chat_sources is preserved
469
- # * receipt-side legacy (neither) -> [:receipt, evidence_address];
470
- # there is no exact rule, so a receipt legacy meta is never merged with
471
- # anything (documented possible overcount for legacy data)
472
- #
473
- # Identity conflicts: when evidence sharing an identity disagree on any
474
- # TOKEN_KEYS value (compared as integers, missing counts as 0) or on
475
- # provider_response_id (two DIFFERENT non-empty values), the event keeps
476
- # every evidence record, counts only the canonical one, sets conflict: true,
477
- # and - when a warnings Array was supplied - appends one Hash per conflicting
478
- # event:
479
- #
480
- # {reason: :identity_conflict, inference_id:, identity:,
481
- # fields: <Array of disputed field symbols>,
482
- # values: <Hash field => the raw meta values in evidence order>,
483
- # evidence: <the event evidence records>}
484
- #
485
- # A missing provider_response_id in one record and a present one in another
486
- # is INCOMPLETE EVIDENCE, not a conflict: one copy simply carries richer
487
- # metadata (e.g. across a metadata-format migration). Such events set
488
- # incomplete_evidence: true, are counted normally, and are never warned about
489
- # as conflicts. The same leniency applies to optional detailed usage fields
490
- # (cct/cwt/rt): only the immutable core (inference identity, pt/ct/tt,
491
- # non-empty provider_response_id) can conflict.
492
- #
493
- # A conflicting event is counted once from its canonical evidence, but that
494
- # number is NOT authoritative: reports must label any total containing
495
- # conflicts as unresolved (see Chat.provenance_token_totals `conflicts:`).
496
- # Pass `strict: true` to raise ScoutException on the first conflict instead.
497
- #
498
- # Checkpoint fields (*_c, *_s) are never read or summed here.
499
- def self.provenance_token_events(root, warnings: nil, strict: false, **traversal_options)
500
- # Route traversal-stage agent_meta problems into the caller's warnings
501
- # Array instead of letting them raise. Other traversal errors stay strict
502
- # (raise), and an explicitly supplied on_error keeps being called.
503
- if Array === warnings
504
- caller_on_error = traversal_options[:on_error]
505
- traversal_options = traversal_options.merge(
506
- on_error: lambda do |error, kind, object, relation, reference|
507
- if relation == :agent_job && reference.is_a?(Hash) && reference[:reason] &&
508
- error.message.to_s.include?('agent_meta receipt')
509
- warnings << reference.merge(message: error.message)
510
- caller_on_error.call(error, kind, object, relation, reference) if caller_on_error
511
- elsif caller_on_error
512
- caller_on_error.call(error, kind, object, relation, reference)
302
+ chats = {}
303
+ delegation = {}
304
+ receipt_warnings = []
305
+
306
+ # The output chat is the transcript this node's own messages live in.
307
+ # A chat root IS that transcript; a job root contributes one only when
308
+ # the job is chat-producing and its result exists. A job's input chat
309
+ # is invocation context, never generated output, and is never read.
310
+ transcript = chat_path || (job_result_chat_file(job) && job_result_chat_file(job).to_s)
311
+ if transcript
312
+ chat = provenance_chat_load(transcript)
313
+
314
+ # Standalone meta: job= messages, anchored at their own message index.
315
+ # Every value is the RESOLVED job's canonical absolute path, so the
316
+ # reference is directly usable with Step.load; the original metadata
317
+ # spelling (often a short path) is intentionally discarded.
318
+ chat.each_with_index do |message, index|
319
+ next unless message[:role].to_s == 'meta'
320
+ job_ref = Chat.parse_meta(message[:content].to_s)[:job]
321
+ next unless job_ref
322
+ begin
323
+ job_step, = resolve_job_reference(job_ref)
324
+ if job_step
325
+ add_indexed_reference(chats, index, provenance_path(:job, job_step))
513
326
  else
514
- raise error
327
+ provenance_error(callback, ScoutException.new(agent_meta_error_message(
328
+ :unresolved_job_reference, chat_path: transcript, output_address: index,
329
+ reference: job_ref)), :chat, transcript, :job, job_ref)
515
330
  end
331
+ rescue StandardError => error
332
+ provenance_error(callback, error, :chat, transcript, :job, job_ref)
516
333
  end
517
- )
518
- end
519
-
520
- files = provenance_chat_files(root, **traversal_options)
521
- sources = {}
522
- files.each { |file| sources[file] = Chat.load(file) }
523
-
524
- evidences = []
525
-
526
- # Chat-side direct events. `deduplicate: false` keeps one entry per
527
- # persisted location: an inference copied into several saved chats/logs
528
- # (or projected into several places) yields several evidence records, one
529
- # per address. Grouping by identity happens exactly once, below, so the
530
- # resulting event can list every location.
531
- trace_chat_sources(sources, false).each do |entry|
532
- meta = entry[:meta]
533
- next if meta[:job]
534
- next unless TOKEN_KEYS.any? { |key| meta.include?(key) }
535
- address = entry[:meta_address]
536
- evidences << {
537
- origin: :chat_meta,
538
- discovery: evidences.length,
539
- source: address ? address[0] : nil,
540
- meta_address: address,
541
- meta: meta,
542
- call_id: nil,
543
- tool_name: nil,
544
- inference_id: entry[:inference_id],
545
- lineage_id: entry[:lineage_id]
546
- }
547
- end
548
-
549
- # Receipt-side direct events. Malformed receipts are reported through a
550
- # private buffer and merged into the caller's warnings Array only when the
551
- # traversal stage has not already reported the same problem (it reports
552
- # with the richer reference + message shape whenever :agent_job is
553
- # followed); without an Array, agent_meta_evidence skips them silently.
554
- receipt_problems = Array === warnings ? [] : nil
555
- sources.each do |path, chat|
556
- agent_meta_evidence(chat, source: path, warnings: receipt_problems).each do |record|
557
- meta = record[:meta]
558
- next if meta[:job]
559
- next unless TOKEN_KEYS.any? { |key| meta.include?(key) }
560
- evidences << {
561
- origin: :agent_meta,
562
- discovery: evidences.length,
563
- source: path,
564
- evidence_address: record[:evidence_address],
565
- output_address: record[:output_address],
566
- agent_meta_index: record[:agent_meta_index],
567
- meta: meta,
568
- call_id: record[:call_id],
569
- tool_name: record[:tool_name],
570
- inference_id: meta[:inference_id],
571
- lineage_id: nil
572
- }
573
334
  end
574
- end
575
335
 
576
- if receipt_problems && !receipt_problems.empty?
577
- reported = Set.new(warnings.collect do |warning|
578
- next if warning[:reason] == :identity_conflict
579
- [warning[:reason], warning[:output_address], warning[:agent_meta_index]]
580
- end)
581
- receipt_problems.each do |problem|
582
- key = [problem[:reason], problem[:output_address], problem[:agent_meta_index]]
583
- warnings << problem unless reported.include?(key)
584
- end
585
- end
586
-
587
- origin_rank = { chat_meta: 0, agent_meta: 1 }
588
- events = []
589
- by_identity = {}
590
-
591
- evidences.each do |evidence|
592
- meta = evidence[:meta]
593
- if evidence[:inference_id]
594
- identity = [:inference_id, evidence[:inference_id]]
595
- deduplication = :inference_id
596
- elsif meta[:provider_response_id]
597
- identity = [:provider_response_id, meta[:provider_response_id]]
598
- deduplication = :provider_response_id
599
- elsif evidence[:origin] == :chat_meta
600
- identity = [:lineage, evidence[:lineage_id]]
601
- deduplication = :legacy_lineage
602
- else
603
- identity = [:receipt, evidence[:evidence_address]]
604
- deduplication = :receipt_unresolved
605
- end
606
-
607
- event = by_identity[identity]
608
- unless event
609
- event = { identity: identity, deduplication: deduplication, _evidence: [] }
610
- by_identity[identity] = event
611
- events << event
612
- end
613
- event[:_evidence] << evidence
614
- end
615
-
616
- events.each do |event|
617
- ordered = event.delete(:_evidence).sort_by do |evidence|
618
- [origin_rank[evidence[:origin]], evidence[:discovery]]
336
+ # agent_meta receipts: job references lifted from function_call_output
337
+ # envelopes, anchored at the outer output message index. Malformed
338
+ # receipts follow the on_error policy; unresolved references are
339
+ # reported, never silently dropped.
340
+ begin
341
+ records = agent_meta_job_references(chat, source: transcript, warnings: receipt_warnings)
342
+ rescue StandardError => error
343
+ provenance_error(callback, error, :chat, transcript, :agent_job, transcript)
344
+ records = []
619
345
  end
620
- canonical = ordered.first
621
-
622
- event[:evidence] = ordered.collect do |evidence|
623
- record = {
624
- origin: evidence[:origin],
625
- source: evidence[:source],
626
- meta: evidence[:meta],
627
- call_id: evidence[:call_id],
628
- tool_name: evidence[:tool_name]
629
- }
630
- if evidence[:origin] == :chat_meta
631
- record[:meta_address] = evidence[:meta_address]
632
- else
633
- record[:evidence_address] = evidence[:evidence_address]
634
- record[:output_address] = evidence[:output_address]
635
- record[:agent_meta_index] = evidence[:agent_meta_index]
346
+ records.each do |record|
347
+ reference = record[:job]
348
+ index = Array === record[:output_address] ? record[:output_address].last : record[:output_address]
349
+ begin
350
+ job_step, = resolve_job_reference(reference)
351
+ unless job_step
352
+ provenance_error(callback, ScoutException.new(agent_meta_error_message(
353
+ :unresolved_job_reference, chat_path: transcript,
354
+ output_address: record[:output_address], call_id: record[:call_id],
355
+ tool_name: record[:tool_name], reference: reference)), :chat, transcript, :agent_job, reference)
356
+ next
357
+ end
358
+ add_indexed_reference(chats, index, provenance_path(:job, job_step))
359
+ rescue StandardError => error
360
+ provenance_error(callback, error, :chat, transcript, :agent_job, reference)
636
361
  end
637
- record
638
- end
639
-
640
- event[:inference_id] = canonical[:inference_id]
641
- event[:meta] = canonical[:meta]
642
- event[:tokens] = TOKEN_KEYS.each_with_object({}) do |key, hash|
643
- hash[key.to_sym] = canonical[:meta][key].to_i
644
362
  end
645
363
 
646
- # Immutable core only: pt/ct/tt and a genuinely different non-empty
647
- # provider_response_id. Optional detail fields (cct, cwt, rt) and a
648
- # missing-vs-present provider_response_id are incomplete evidence, not
649
- # conflicts.
650
- core_fields = %i[pt ct tt]
651
- fields = []
652
- values = {}
653
- core_fields.each do |key|
654
- next unless ordered.collect { |evidence| evidence[:meta][key].to_i }.uniq.length > 1
655
- fields << key
656
- values[key] = ordered.collect { |evidence| evidence[:meta][key] }
657
- end
658
- provider_ids = ordered.collect { |evidence| evidence[:meta][:provider_response_id].to_s }
659
- .reject { |value| value.strip.empty? }.uniq
660
- if provider_ids.length > 1
661
- fields << :provider_response_id
662
- values[:provider_response_id] = ordered.collect { |evidence| evidence[:meta][:provider_response_id] }
364
+ # Actual ask calls only: an ask that produced no job= receipt is a
365
+ # delegation relationship, not an inference-job one.
366
+ begin
367
+ tool_calls(chat).each do |call|
368
+ next unless call[:name] == 'ask'
369
+ arguments = call[:arguments]
370
+ arguments = Chat.parse_json(arguments) if String === arguments
371
+ next unless Hash === arguments && arguments['agent']
372
+ agent = arguments['agent'].to_s
373
+ conversation = arguments['conversation']
374
+ conversation = 'default' if conversation.nil? || conversation.to_s.empty?
375
+ add_indexed_reference(delegation, call[:call_index], "#{agent}##{conversation}")
376
+ end
377
+ rescue StandardError => error
378
+ provenance_error(callback, error, :chat, transcript, :ask, transcript)
663
379
  end
380
+ end
381
+ receipt_warnings.each { |warning| warnings << {kind: :agent_meta, warning: warning} }
664
382
 
665
- # Incomplete evidence: exactly one non-empty provider_response_id value
666
- # while at least one copy lacks it (metadata-format migration), so there
667
- # is nothing to disagree about.
668
- present_ids = ordered.collect { |evidence| evidence[:meta][:provider_response_id].to_s }
669
- .reject { |value| value.strip.empty? }
670
- if present_ids.uniq.length <= 1 &&
671
- present_ids.length != ordered.length && !present_ids.empty?
672
- event[:incomplete_evidence] = true
383
+ # Direct dependencies as canonical absolute paths (realpath when
384
+ # available), declared order preserved, directly loadable by Step.load.
385
+ dependencies = []
386
+ if job
387
+ begin
388
+ dependencies = job.dependencies.collect { |dependency| provenance_path(:job, dependency) }
389
+ rescue StandardError => error
390
+ provenance_error(callback, error, :job, job, :dependency, job)
673
391
  end
392
+ end
674
393
 
675
- next unless fields.any?
676
- event[:conflict] = true
677
- if strict
678
- raise ScoutException, "agent_meta identity conflict on #{event[:identity] * '='}: disputed #{fields * ','}"
679
- end
680
- next unless Array === warnings
681
- warnings << {
682
- reason: :identity_conflict,
683
- inference_id: event[:inference_id],
684
- identity: event[:identity],
685
- fields: fields,
686
- values: values,
687
- evidence: event[:evidence]
688
- }
394
+ live = begin
395
+ files_dir = root_kind == :job ? job.files_dir : chat_path + '.files'
396
+ direct_log_chat_files(files_dir).collect(&:to_s)
397
+ rescue StandardError => error
398
+ provenance_error(callback, error, root_kind, root, :log, files_dir)
399
+ []
689
400
  end
690
401
 
691
- # Reorder keys readably; conflict defaults to false.
692
- events.collect do |event|
693
- {
694
- inference_id: event[:inference_id],
695
- identity: event[:identity],
696
- deduplication: event[:deduplication],
697
- meta: event[:meta],
698
- tokens: event[:tokens],
699
- evidence: event[:evidence],
700
- conflict: event[:conflict] || false,
701
- incomplete_evidence: event[:incomplete_evidence] || false
702
- }
402
+ {type: root_kind, chats: chats, dependencies: dependencies,
403
+ delegation: delegation, live: live, warnings: warnings}
404
+ end
405
+
406
+ # Add +value+ at integer +index+, keeping an existing scalar distinct from
407
+ # later values at the same index (both forms are then an Array).
408
+ def self.add_indexed_reference(map, index, value)
409
+ return unless Integer === index
410
+ current = map[index]
411
+ if current.nil?
412
+ map[index] = value
413
+ elsif current != value
414
+ map[index] = Array === current ? (current.include?(value) ? current : current + [value]) : [current, value]
703
415
  end
704
416
  end
705
417
 
706
- # Aggregate token totals over deduplicated provenance events. The result is
707
- # symbol keyed and zero initialized exactly like Chat.token_totals:
708
- # {pt:, ct:, tt:, cct:, cwt:, rt:}.
709
- #
710
- # Scopes. These are EVIDENCE COVERAGE descriptions, not a partition of cost:
711
- # an event represented both in a saved child log and in a receipt belongs to
712
- # :chat_evidence AND to :receipt_evidence, so the two are not additive and
713
- # must never be summed together. Only :deduplicated_total and :receipt_only
714
- # are safe to compare additively.
715
- #
716
- # * :deduplicated_total - every event counted once (default);
717
- # * :chat_evidence - events with at least one :chat_meta evidence
718
- # (physically stored in a chat/log file);
719
- # * :receipt_evidence - events with at least one :agent_meta evidence
720
- # (embedded in a function_call_output receipt);
721
- # * :receipt_only - events with receipt evidence and NO saved-chat
722
- # evidence (the disjoint delegated contribution).
723
- #
724
- # Conflict handling: a conflicting event still contributes its canonical
725
- # tokens, so a total containing conflicts is a best-effort view, not an
726
- # authoritative cost. The `conflicts:` keyword makes that explicit in
727
- # machine readable form; with `strict: true` conflicts raise instead (the
728
- # keyword is forwarded to provenance_token_events).
729
- def self.provenance_token_totals(root, scope: :deduplicated_total, warnings: nil,
730
- conflicts: nil, **traversal_options)
731
- events = provenance_token_events(root, warnings: warnings, **traversal_options)
732
-
733
- selected = case scope.to_sym
734
- when :deduplicated_total
735
- events
736
- when :chat_evidence
737
- events.select { |event| event[:evidence].any? { |e| e[:origin] == :chat_meta } }
738
- when :receipt_evidence
739
- events.select { |event| event[:evidence].any? { |e| e[:origin] == :agent_meta } }
740
- when :receipt_only
741
- events.select do |event|
742
- event[:evidence].any? { |e| e[:origin] == :agent_meta } &&
743
- event[:evidence].none? { |e| e[:origin] == :chat_meta }
418
+ # RECURSIVE closure entry point: one-pass materialized object graph over
419
+ # the whole provenance tree, for collectors and cross-chat analysis. The
420
+ # default collects traversal errors in `warnings`; pass a callback to
421
+ # receive them as well, or `on_error: :raise` for strict behavior.
422
+ def self.provenance_closure(root, root_type: nil, follow: :all, on_error: :collect)
423
+ warnings = []
424
+ callback = if on_error == :raise
425
+ nil
426
+ elsif on_error.respond_to?(:call)
427
+ lambda do |error, kind, object, relation, reference|
428
+ warnings << provenance_warning(error, kind, object, relation, reference)
429
+ on_error.call(error, kind, object, relation, reference)
744
430
  end
745
431
  else
746
- raise ParameterException, "Unknown token scope: #{scope}"
432
+ lambda do |error, kind, object, relation, reference|
433
+ warnings << provenance_warning(error, kind, object, relation, reference)
434
+ end
747
435
  end
748
436
 
749
- totals = TOKEN_KEYS.each_with_object({}) { |key, hash| hash[key.to_sym] = 0 }
750
- selected.each do |event|
751
- TOKEN_KEYS.each { |key| totals[key.to_sym] += event[:tokens][key.to_sym] }
752
- end
437
+ chats, jobs, edges, edge_keys = {}, {}, [], Set.new
438
+ resolved_kind = (root_type || (Step === root ? :job : :chat)).to_sym
439
+ resolved_root = if resolved_kind == :job
440
+ Step === root ? root : Step.load(root)
441
+ else
442
+ path = File.expand_path(root.to_s)
443
+ raise ParameterException, "Chat not found: #{root}" unless File.file?(path)
444
+ Path.setup(path)
445
+ end
446
+
447
+ traverse_provenance(resolved_root, root_type: resolved_kind, follow: follow, on_error: callback) do |kind, object, parent_kind, parent, relation, first, detail|
448
+ if first
449
+ path = provenance_path(kind, object)
450
+ (kind == :chat ? chats : jobs)[path] ||= (kind == :chat ? provenance_chat_load(object) : object)
451
+ end
452
+ next unless parent
453
+
454
+ from = provenance_path(parent_kind, parent)
455
+ to = provenance_path(kind, object)
456
+ identity = [parent_kind, from, relation, kind, to]
457
+ identity << (detail && detail[:evidence_address]) if relation == :agent_job
458
+ next unless edge_keys.add?(identity)
753
459
 
754
- if conflicts.is_a?(Hash)
755
- conflicting = events.select { |event| event[:conflict] }
756
- incomplete = events.select { |event| event[:incomplete_evidence] }
757
- conflicts[:events] = conflicting.length
758
- conflicts[:incomplete_evidence_events] = incomplete.length
759
- conflicts[:authoritative] = conflicting.empty?
460
+ edges << {from_kind: parent_kind, from: parent, relation: relation,
461
+ to_kind: kind, to: object, detail: detail}
760
462
  end
761
463
 
762
- totals
464
+ {root_kind: resolved_kind, root: resolved_root, chats: chats,
465
+ jobs: jobs, edges: edges, warnings: warnings}
466
+ end
467
+
468
+ def self.provenance_warning(error, kind, object, relation, reference)
469
+ {kind: kind, path: provenance_path(kind, object), relation: relation,
470
+ reference: reference, error: error.message}
763
471
  end
764
472
 
765
- # Provenance token aggregate. Receipt (agent_meta) child usage is now
766
- # included through the event collector, so child inference paid inside a
767
- # parent tool call is no longer invisible when the child chat was not saved.
768
- def self.tokens(root, **options)
769
- provenance_token_totals(root, **options)
473
+ # Compatibility collectors. They expose the recursive closure; prefer
474
+ # provenance_graph for one node's immediate provenance.
475
+ def self.provenance_edges(root, on_error: :raise, **options)
476
+ provenance_closure(root, on_error: on_error, **options)[:edges]
770
477
  end
771
478
 
772
- def self.timestamp
773
- Time.now.utc.iso8601(3)
479
+ def self.provenance_chat_files(root, on_error: :raise, **options)
480
+ provenance_closure(root, on_error: on_error, **options)[:chats].keys
481
+ end
482
+
483
+ def self.provenance_jobs(root, on_error: :raise, **options)
484
+ provenance_closure(root, on_error: on_error, **options)[:jobs].values
485
+ end
486
+
487
+ # Former chat-to-chat collector retained for existing callers.
488
+ def self.provenance(chat_file, prov = {})
489
+ traverse_provenance(chat_file) do |kind, object, parent_kind, parent, _relation, _first|
490
+ next unless parent && kind == :chat
491
+ parent_path = provenance_path(parent_kind, parent)
492
+ prov[parent_path] ||= []
493
+ path = provenance_path(kind, object)
494
+ prov[parent_path] << path unless prov[parent_path].include?(path)
495
+ end
496
+ prov
774
497
  end
775
498
  end
499
+
500
+ require_relative 'provenance/tokens'
501
+ require_relative 'provenance/live'