scout-ai 2.1.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (186) hide show
  1. checksums.yaml +4 -4
  2. data/.vimproject +133 -58
  3. data/README.md +2 -1
  4. data/VERSION +1 -1
  5. data/doc/Improvements.md +490 -148
  6. data/doc/Model.md +53 -10
  7. data/doc/StartHere.md +44 -19
  8. data/doc/developer/Architecture.md +25 -6
  9. data/doc/developer/Backends.md +207 -48
  10. data/doc/developer/ChatLifecycle.md +121 -20
  11. data/doc/developer/DelegationInternals.md +319 -33
  12. data/doc/developer/DesignPrinciples.md +205 -16
  13. data/doc/developer/PathEngine.md +628 -0
  14. data/doc/developer/PromptProcessing.md +332 -82
  15. data/doc/developer/Provenance.md +388 -40
  16. data/doc/developer/Sandbox.md +213 -0
  17. data/doc/user/BuildingAgents.md +130 -18
  18. data/doc/user/Cookbook.md +29 -8
  19. data/doc/user/CoreConcepts.md +7 -6
  20. data/doc/user/Delegation.md +166 -15
  21. data/doc/user/GettingStarted.md +20 -16
  22. data/doc/user/ManagingContext.md +155 -17
  23. data/doc/user/MultiAgentWorkflows.md +105 -15
  24. data/doc/user/Python.md +11 -1
  25. data/doc/user/RunningInference.md +90 -47
  26. data/doc/user/ToolCalling.md +134 -29
  27. data/doc/user/WritingChats.md +56 -27
  28. data/lib/scout/llm/agent/attach.rb +13 -17
  29. data/lib/scout/llm/agent/chat.rb +32 -0
  30. data/lib/scout/llm/agent/construction.rb +64 -0
  31. data/lib/scout/llm/agent/conversation.rb +304 -0
  32. data/lib/scout/llm/agent/delegate.rb +56 -238
  33. data/lib/scout/llm/agent/path/edit.rb +230 -0
  34. data/lib/scout/llm/agent/path/patch.rb +252 -0
  35. data/lib/scout/llm/agent/path/workflow_kinds.rb +175 -0
  36. data/lib/scout/llm/agent/path.rb +1777 -0
  37. data/lib/scout/llm/agent/save.rb +11 -9
  38. data/lib/scout/llm/agent/workflow.rb +77 -16
  39. data/lib/scout/llm/agent.rb +147 -31
  40. data/lib/scout/llm/ask.rb +28 -17
  41. data/lib/scout/llm/backends/anthropic.rb +1 -1
  42. data/lib/scout/llm/backends/bedrock.rb +3 -2
  43. data/lib/scout/llm/backends/default.rb +127 -34
  44. data/lib/scout/llm/backends/glm.rb +28 -1
  45. data/lib/scout/llm/backends/huggingface.rb +1 -1
  46. data/lib/scout/llm/backends/ollama.rb +1 -1
  47. data/lib/scout/llm/backends/openai.rb +7 -6
  48. data/lib/scout/llm/backends/openwebui.rb +14 -7
  49. data/lib/scout/llm/backends/relay.rb +8 -2
  50. data/lib/scout/llm/chat/agent_meta.rb +24 -60
  51. data/lib/scout/llm/chat/parse.rb +1 -1
  52. data/lib/scout/llm/chat/process/files.rb +10 -0
  53. data/lib/scout/llm/chat/process/meta.rb +5 -7
  54. data/lib/scout/llm/chat/process/tools.rb +104 -49
  55. data/lib/scout/llm/chat/prompt/epoch_tool_compactation.rb +355 -0
  56. data/lib/scout/llm/chat/prompt/inbox.rb +188 -0
  57. data/lib/scout/llm/chat/prompt/shorten_tools.rb +797 -13
  58. data/lib/scout/llm/chat/prompt/shorten_tools_epoch.rb +1 -365
  59. data/lib/scout/llm/chat/prompt/shorten_tools_epoch_increment.rb +1 -0
  60. data/lib/scout/llm/chat/prompt.rb +24 -10
  61. data/lib/scout/llm/chat/provenance/live.rb +1080 -0
  62. data/lib/scout/llm/chat/provenance/tokens.rb +386 -0
  63. data/lib/scout/llm/chat/provenance.rb +343 -676
  64. data/lib/scout/llm/chat.rb +8 -2
  65. data/lib/scout/llm/embed.rb +15 -3
  66. data/lib/scout/llm/image.rb +4 -1
  67. data/lib/scout/llm/mcp.rb +4 -2
  68. data/lib/scout/llm/request_context.rb +234 -0
  69. data/lib/scout/llm/sandbox.rb +263 -0
  70. data/lib/scout/llm/tools/call.rb +163 -42
  71. data/lib/scout/llm/tools/definition.rb +48 -0
  72. data/lib/scout/llm/tools/knowledge_base.rb +1 -0
  73. data/lib/scout/llm/tools/mcp.rb +50 -43
  74. data/lib/scout/llm/tools/workflow.rb +90 -20
  75. data/lib/scout/llm/tools.rb +14 -41
  76. data/lib/scout/model/decision/base.rb +43 -0
  77. data/lib/scout/model/decision/jev.rb +161 -0
  78. data/lib/scout/model/python/torch.rb +1 -1
  79. data/research/clear-tools-inherit.md +171 -0
  80. data/research/path-engine-dc1-dc2-dc3-fixes.md +279 -0
  81. data/research/path-kind-chat-role.md +96 -0
  82. data/research/path-kind-contract-fixes-engine.md +307 -0
  83. data/research/scout-ai-runtime-availability.md +65 -0
  84. data/research/subsys/README.md +127 -0
  85. data/research/subsys/agent-delegation.md +201 -0
  86. data/research/subsys/agent-society.md +275 -0
  87. data/research/subsys/agentworkflow.md +233 -0
  88. data/research/subsys/backends.md +221 -0
  89. data/research/subsys/chat.md +314 -0
  90. data/research/subsys/embed-image.md +244 -0
  91. data/research/subsys/entry-cli.md +253 -0
  92. data/research/subsys/model-ml.md +326 -0
  93. data/research/subsys/provenance.md +290 -0
  94. data/research/subsys/tools.md +334 -0
  95. data/scout-ai.gemspec +71 -27
  96. data/scout_commands/agent/ask +8 -7
  97. data/scout_commands/llm/abridged +40 -0
  98. data/scout_commands/llm/ask +9 -9
  99. data/scout_commands/llm/md +2 -0
  100. data/scout_commands/llm/prov +724 -59
  101. data/scout_commands/llm/word +4 -0
  102. data/share/word/reference.docx +0 -0
  103. data/test/integration/scout/model/decision/test_jev.rb +144 -0
  104. data/test/scout/llm/agent/test_attach.rb +117 -0
  105. data/test/scout/llm/agent/test_conversation.rb +407 -0
  106. data/test/scout/llm/agent/test_delegate.rb +209 -0
  107. data/test/scout/llm/agent/test_path.rb +1812 -0
  108. data/test/scout/llm/agent/test_path_edit.rb +908 -0
  109. data/test/scout/llm/agent/test_path_errors.rb +390 -0
  110. data/test/scout/llm/agent/test_path_filesystem.rb +532 -0
  111. data/test/scout/llm/agent/test_path_patch.rb +233 -0
  112. data/test/scout/llm/agent/test_path_promotion.rb +386 -0
  113. data/test/scout/llm/agent/test_path_workflow_integration.rb +665 -0
  114. data/test/scout/llm/agent/test_save.rb +70 -15
  115. data/test/scout/llm/agent/test_workflow.rb +130 -4
  116. data/test/scout/llm/backends/test_anthropic.rb +4 -4
  117. data/test/scout/llm/backends/test_bedrock.rb +4 -4
  118. data/test/scout/llm/backends/test_format_other.rb +43 -0
  119. data/test/scout/llm/backends/test_ollama.rb +2 -2
  120. data/test/scout/llm/backends/test_openwebui.rb +12 -8
  121. data/test/scout/llm/backends/test_reasoning.rb +114 -0
  122. data/test/scout/llm/chat/agent_meta_fixtures.rb +28 -27
  123. data/test/scout/llm/chat/prompt/test_epoch_tool_compactation.rb +612 -0
  124. data/test/scout/llm/chat/prov_plot_fixtures.rb +131 -0
  125. data/test/scout/llm/chat/test_agent_meta.rb +40 -80
  126. data/test/scout/llm/chat/test_agent_meta_provenance.rb +67 -28
  127. data/test/scout/llm/chat/test_agent_meta_tokens.rb +59 -8
  128. data/test/scout/llm/chat/test_agent_view.rb +178 -0
  129. data/test/scout/llm/chat/test_live_report.rb +282 -0
  130. data/test/scout/llm/chat/test_live_workload.rb +193 -0
  131. data/test/scout/llm/chat/test_parse.rb +32 -2
  132. data/test/scout/llm/chat/test_prompt.rb +411 -0
  133. data/test/scout/llm/chat/test_prov_cli.rb +310 -15
  134. data/test/scout/llm/chat/test_prov_cli_live.rb +152 -0
  135. data/test/scout/llm/chat/test_prov_plot.rb +213 -0
  136. data/test/scout/llm/chat/test_prov_timeline.rb +355 -0
  137. data/test/scout/llm/chat/test_provenance.rb +67 -22
  138. data/test/scout/llm/chat/test_provenance_index.rb +479 -0
  139. data/test/scout/llm/chat/test_society_view.rb +159 -0
  140. data/test/scout/llm/test_agent.rb +1 -1
  141. data/test/scout/llm/test_embed.rb +103 -1
  142. data/test/scout/llm/test_request_context.rb +299 -0
  143. data/test/scout/llm/test_sandbox.rb +249 -0
  144. data/test/scout/llm/tools/test_agent_pairing.rb +150 -0
  145. data/test/scout/llm/tools/test_call_delegation_conflict.rb +316 -0
  146. data/test/scout/llm/tools/test_definition.rb +332 -0
  147. data/test/scout/llm/tools/test_jobs_file.rb +211 -0
  148. data/test/scout/llm/tools/test_mcp.rb +37 -8
  149. data/test/scout/llm/tools/test_workflow.rb +45 -1
  150. data/test/scout/model/decision/test_jev.rb +453 -0
  151. data/test/scout/model/python/huggingface/causal/test_next_token.rb +7 -10
  152. data/test/scout/model/python/huggingface/test_causal.rb +11 -2
  153. data/test/scout/model/python/huggingface/test_classification.rb +5 -3
  154. data/test/scout/model/python/test_availability.rb +116 -0
  155. data/test/scout/model/python/test_torch.rb +54 -2
  156. data/test/support/availability.rb +72 -174
  157. data/test/support/fake_clients.rb +18 -9
  158. data/test/support/fixtures.rb +75 -6
  159. data/test/support/mock_backend.rb +9 -1
  160. data/test/support/test_fixtures.rb +156 -0
  161. data/test/test_helper.rb +14 -4
  162. metadata +70 -26
  163. data/research/ChatAnalyst-required-changes.md +0 -167
  164. data/research/agent-delegation-analysis.md +0 -810
  165. data/research/agent-meta-provenance-integration-plan.md +0 -622
  166. data/research/agent-workflow-analysis.md +0 -1120
  167. data/research/backends-analysis.md +0 -836
  168. data/research/chat-core-analysis.md +0 -946
  169. data/research/chatanalyst-provenance/00-baseline.md +0 -30
  170. data/research/chatanalyst-provenance/01-repo-map.md +0 -60
  171. data/research/chatanalyst-provenance/02-event-reconstruction.md +0 -55
  172. data/research/chatanalyst-provenance/03-duplication-evidence.md +0 -45
  173. data/research/chatanalyst-provenance/04-tooling-root-cause.md +0 -57
  174. data/research/chatanalyst-provenance/05-fix-plan.md +0 -46
  175. data/research/chatanalyst-provenance/07-critic-review.md +0 -25
  176. data/research/chatanalyst-provenance/final-report.md +0 -45
  177. data/research/chatanalyst-provenance/resumption.md +0 -37
  178. data/research/coding-philosophy-analysis.md +0 -928
  179. data/research/commands-analysis.md +0 -947
  180. data/research/multi-agent-patterns-analysis.md +0 -853
  181. data/research/prompt-strategies-analysis.md +0 -630
  182. data/research/prov-verbosity-fix-notes.md +0 -77
  183. data/research/provenance-analysis.md +0 -469
  184. data/research/provenance-continuation-accounting.md +0 -255
  185. data/research/synthesis-report.md +0 -487
  186. data/research/tools-system-analysis.md +0 -779
@@ -3,85 +3,28 @@ 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
6
8
 
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) }
32
- .select { |file| File.file?(file) }
33
- .uniq
34
- .sort
35
- .collect { |file| Path.setup(file) }
36
- end
37
-
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
- def self.direct_job_chat_files(job)
45
- job = Step.load(job) unless Step === job
46
- direct_log_chat_glob(job.files_dir)
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
47
16
  end
48
17
 
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.
68
- def self.direct_chat_sidecar_files(path)
69
- files_dir = path.to_s + '.files'
70
- 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
75
- end
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] ||= {}
76
24
  end
77
25
 
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
- def self.job_result_chat_file(job)
82
- job = Step.load(job) unless Step === job
83
- return nil unless job.type.to_s == 'chat' && File.file?(job.path.to_s)
84
- Path.setup(File.expand_path(job.path.to_s))
26
+ def self.close_provenance_run_cache
27
+ Thread.current[PROVENANCE_CACHE_KEY] = nil
85
28
  end
86
29
 
87
30
  def self.provenance_path(kind, object)
@@ -95,184 +38,122 @@ module Chat
95
38
  [kind.to_sym, provenance_path(kind, object)]
96
39
  end
97
40
 
98
- # ------------------------------------------------------------------
99
- # Run-scoped, parse-once chat cache (review theme 04, stage s1)
100
- # ------------------------------------------------------------------
101
- # A provenance "run" is one top-level call to a public provenance entry
102
- # point (traverse_provenance, provenance_token_events,
103
- # provenance_token_totals / tokens, and the collectors delegating to them).
104
- # Inside a run every chat file is parsed at most once, keyed by the same
105
- # realpath discipline as node identity (provenance_path), so a file reached
106
- # through several addresses - symlinks, or a chat-typed job whose result
107
- # path equals a chat node path - is parsed once and never double counted.
108
- #
109
- # Guards:
110
- # * lifetime: the cache exists only while a run is active and is dropped
111
- # when it ends, so a live session that appends between two runs is
112
- # always re-parsed (no cross-run persistence);
113
- # * identity: realpath keyed, exactly like provenance nodes;
114
- # * transparency: no envelope shape, traversal order or deduplication
115
- # semantics change - the same Chat object is simply reused within the
116
- # run, and everything downstream only reads it.
117
- def self.with_provenance_run_cache
118
- previous = Thread.current[:scout_ai_provenance_run_cache]
119
- Thread.current[:scout_ai_provenance_run_cache] ||= {}
120
- begin
121
- yield
122
- ensure
123
- Thread.current[:scout_ai_provenance_run_cache] = previous
124
- end
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)
125
45
  end
126
46
 
127
- # Manual scope control for linear, top-level callers such as the `prov`
128
- # SOPT script, whose body cannot be wrapped in a block without reindenting
129
- # the whole file. Open at the start of the run, close when it ends; an
130
- # open scope makes nested with_provenance_run_cache calls reuse it.
131
- def self.open_provenance_run_cache
132
- Thread.current[:scout_ai_provenance_run_cache] ||= {}
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) }
53
+ .select { |file| File.file?(file) }
54
+ .uniq.sort.map { |file| Path.setup(file) }
133
55
  end
134
56
 
135
- def self.close_provenance_run_cache
136
- Thread.current[:scout_ai_provenance_run_cache] = nil
57
+ def self.direct_job_chat_files(job)
58
+ job = Step.load(job) unless Step === job
59
+ direct_log_chat_files(job.files_dir)
137
60
  end
138
61
 
139
- # Chat.load with the run cache applied. Outside a run this parses
140
- # directly, exactly like Chat.load.
141
- def self.provenance_chat_load(path)
142
- cache = Thread.current[:scout_ai_provenance_run_cache]
143
- return Chat.load(path) unless cache
144
- cache[provenance_path(:chat, path)] ||= Chat.load(path)
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.
64
+ def self.direct_chat_sidecar_files(path)
65
+ files_dir = path.to_s + '.files'
66
+ return [] unless File.directory?(files_dir)
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
+ end
145
76
  end
146
77
 
147
- def self.provenance_error(on_error, error, kind, object, relation, reference)
148
- raise error unless on_error
149
- on_error.call(error, kind, object, relation, reference)
78
+ def self.job_result_chat_file(job)
79
+ job = Step.load(job) unless Step === job
80
+ return unless job.type.to_s == 'chat' && File.file?(job.path.to_s)
81
+ Path.setup(File.expand_path(job.path.to_s))
150
82
  end
151
83
 
152
- # Resolve a job reference from a chat meta message into a Step. References
153
- # like "Planned/ask/Default_abc.chat" are relative workflow paths. Step.load
154
- # may resolve them to a Scout-specific directory that does not contain the
155
- # actual job data, so we fall back to checking Rbbt.var.jobs and Scout.var.jobs.
156
- def self.load_job_reference(reference)
157
- return reference if Step === reference
158
- ref_str = reference.to_s
84
+ def self.job_reference_fallback_bases
85
+ ['~/.rbbt/var/jobs', Scout.var.jobs.find.to_s].map { |base| File.expand_path(base) }
86
+ end
159
87
 
160
- step = Step.load(ref_str)
161
- return step if File.exist?(step.path.to_s) || File.exist?(step.path.to_s + '.info')
88
+ def self.job_reference_candidate?(path)
89
+ File.exist?(path.to_s) || File.exist?(path.to_s + '.info')
90
+ end
162
91
 
163
- # Step.load resolves relative workflow paths (e.g. Planned/ask/Default_xyz.chat)
164
- # via Path.find, which may point to a directory that does not contain the
165
- # actual job data (e.g. ~/.scout/ instead of ~/.rbbt/var/jobs/). Try the
166
- # standard Rbbt workflow storage location as a fallback.
167
- rbbt_candidate = File.expand_path(File.join('~/.rbbt/var/jobs', ref_str))
168
- return Step.load(rbbt_candidate) if File.exist?(rbbt_candidate) || File.exist?(rbbt_candidate + '.info')
92
+ def self.load_job_reference(reference)
93
+ return reference if Step === reference
94
+ ref = reference.to_s
95
+ step = Step.load(ref)
96
+ return step if job_reference_candidate?(step.path)
169
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
170
102
  step
171
103
  end
172
104
 
173
- # Resolve one job reference into a usable Step. Returns [step, nil] when the
174
- # job data is loadable (path or .info sidecar exists) and [nil, step] when the
175
- # reference resolves to a directory without job data, keeping the would-be
176
- # step for diagnostics. Used by the :agent_job relation so unresolved
177
- # receipt references are reported instead of enqueued.
178
105
  def self.resolve_job_reference(reference)
179
106
  step = load_job_reference(reference)
180
- path = step.path.to_s
181
- if File.exist?(path) || File.exist?(path + '.info')
182
- [step, nil]
183
- else
184
- [nil, step]
185
- 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)
186
113
  end
187
114
 
188
- # Diagnostics for agent_meta receipt problems found while expanding one chat
189
- # node: malformed receipts collected by Chat.agent_meta_job_references.
190
- # Provenance is only ever extracted from parsed function_call_output JSON
191
- # Hashes carrying an explicit receipt key (current `meta`, legacy
192
- # `agent_meta`); raw output text is never
193
- # inspected, so output content that merely mentions "agent_meta" cannot
194
- # produce a warning. Each malformed record becomes one Chat.provenance_error
195
- # call with relation :agent_job and kind/object :chat + the chat path, so
196
- # strict mode (no on_error) raises ScoutException while warning mode keeps
197
- # going. Returns the valid job references so the caller can enqueue them
198
- # afterwards.
199
115
  def self.report_agent_meta_problems(chat, object, on_error = nil)
200
116
  warnings = []
201
117
  references = agent_meta_job_references(chat, source: object, warnings: warnings)
202
-
203
118
  warnings.each do |warning|
204
119
  error = ScoutException.new(
205
120
  agent_meta_error_message(warning[:reason],
206
- chat_path: object.to_s,
207
- output_address: warning[:output_address],
208
- call_id: warning[:call_id],
209
- tool_name: warning[:tool_name],
210
- 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])
211
124
  )
212
- reference = agent_meta_error_reference(reason: warning[:reason],
213
- source: warning[:source] || object.to_s,
214
- output_address: warning[:output_address],
215
- evidence_address: warning[:evidence_address],
216
- call_id: warning[:call_id],
217
- tool_name: warning[:tool_name],
218
- agent_meta_index: warning[:agent_meta_index],
219
- raw_entry: warning[:raw_entry],
220
- reference: warning[:reference])
221
- 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)
222
132
  end
223
-
224
133
  references
225
134
  end
226
135
 
227
- # Traverse the heterogeneous provenance graph using native Path and Step
228
- # values. The block receives:
229
- #
230
- # kind, object, parent_kind, parent, relation, first_visit, detail
231
- #
232
- # `kind` is :chat or :job. Chat objects are persisted file Paths; jobs are
233
- # Steps. The root has nil parent/relation. Every structural edge is yielded,
234
- # including an edge to a node visited through another branch; first_visit is
235
- # false in that case and the node is not expanded again.
236
- #
237
- # `detail` is nil for every ordinary edge. For an :agent_job edge it is the
238
- # agent_meta receipt record (Chat.agent_meta_job_references entry) that
239
- # produced the edge, so the originating function output address, receipt
240
- # address, call id and tool name stay auditable without re-parsing the parent
241
- # chat. Blocks accepting only the first six arguments keep working; the
242
- # trailing detail is only passed when the block can receive it (or accepts
243
- # any number of arguments).
244
- #
245
- # Relations describe root-outward discovery, not diagram arrow direction:
246
- # chat -> producer job (:job), chat -> delegated-agent producer job
247
- # (:agent_job, from agent_meta receipts), job -> dependency (:dependency),
248
- # job -> log chat (:log), job -> result chat (:result), and chat -> log chat
249
- # of its own .files sidecar (:log, saved agent conversations, excluding the
250
- # root copy at <path>.files/log/agent.chat).
251
- #
252
- # Imported and continued chats are a chat-compilation concern, not a
253
- # provenance concern. They are resolved during Chat.parse and their content
254
- # is already inlined in the persisted chat file. Provenance traversal
255
- # 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.
256
143
  def self.traverse_provenance(root, root_type: nil, follow: :all, on_error: nil, &block)
257
144
  return enum_for(__method__, root, root_type: root_type, follow: follow, on_error: on_error) unless block
258
- unless Thread.current[:scout_ai_provenance_run_cache]
145
+ unless Thread.current[PROVENANCE_CACHE_KEY]
259
146
  return with_provenance_run_cache do
260
147
  traverse_provenance(root, root_type: root_type, follow: follow, on_error: on_error, &block)
261
148
  end
262
149
  end
263
- # Lambda blocks have strict arity; keep six-argument callbacks compatible
264
- # by only yielding the trailing detail when the block can receive it.
265
- detail_arity = lambda do
266
- return true if block.arity == -1
267
- block.arity >= 7
268
- end
269
150
 
270
- relations = follow == :all ? PROVENANCE_RELATIONS : Array(follow).collect(&:to_sym)
151
+ relations = follow == :all ? PROVENANCE_RELATIONS : Array(follow).map(&:to_sym).uniq
271
152
  unknown = relations - PROVENANCE_RELATIONS
272
- raise ParameterException, "Unknown provenance relations: #{unknown * ', '}" if unknown.any?
153
+ raise ParameterException, "Unknown provenance relations: #{unknown.join(', ')}" unless unknown.empty?
273
154
 
274
- root_kind = root_type && root_type.to_sym
275
- 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)
276
157
  root_object = if root_kind == :job
277
158
  Step === root ? root : Step.load(root)
278
159
  else
@@ -281,30 +162,30 @@ module Chat
281
162
  Path.setup(path)
282
163
  end
283
164
 
284
- queue = [[root_kind, root_object, nil, nil, nil]]
165
+ queue = [[root_kind, root_object, nil, nil, nil, nil]]
285
166
  seen = Set.new
167
+ cursor = 0
168
+ wants_detail = block.arity == -1 || block.arity >= 7 ||
169
+ block.parameters.any? { |kind, _name| kind == :rest }
286
170
 
287
- until queue.empty?
288
- 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
289
174
  key = provenance_key(kind, object)
290
- first_visit = !seen.include?(key)
291
- if detail_arity.call
292
- block.call(kind, object, parent_kind, parent, relation, first_visit, detail)
293
- else
294
- block.call(kind, object, parent_kind, parent, relation, first_visit)
295
- end
296
- 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
297
180
  seen << key
298
181
 
299
182
  begin
300
183
  if kind == :chat
301
184
  chat = provenance_chat_load(object)
302
-
303
185
  if relations.include?(:job)
304
186
  chat.jobs.each do |reference|
305
187
  begin
306
- job = load_job_reference(reference)
307
- queue << [:job, job, :chat, object, :job]
188
+ queue << [:job, load_job_reference(reference), :chat, object, :job, nil]
308
189
  rescue StandardError => error
309
190
  provenance_error(on_error, error, :chat, object, :job, reference)
310
191
  end
@@ -312,523 +193,309 @@ module Chat
312
193
  end
313
194
 
314
195
  if relations.include?(:agent_job)
315
- # Malformed receipts are diagnostics, never provenance; they are
316
- # reported through provenance_error and skipped.
317
- references = begin
318
- report_agent_meta_problems(chat, object, on_error)
319
- rescue StandardError => error
320
- provenance_error(on_error, error, :chat, object, :agent_job, object)
321
- []
322
- end
323
-
324
- 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|
325
203
  reference = record[:job]
326
204
  begin
327
- job, _unresolved = resolve_job_reference(reference)
205
+ job, = resolve_job_reference(reference)
328
206
  if job
329
- # The receipt record travels with the edge as its detail so
330
- # the traversal keeps the originating output address, call
331
- # id and receipt index.
332
207
  queue << [:job, job, :chat, object, :agent_job, record]
333
208
  else
334
- error = ScoutException.new(
335
- agent_meta_error_message(:unresolved_job_reference,
336
- chat_path: object.to_s,
337
- output_address: record[:output_address],
338
- call_id: record[:call_id],
339
- tool_name: record[:tool_name],
340
- reference: reference)
341
- )
342
- provenance_error(on_error, error, :chat, object, :agent_job,
343
- agent_meta_error_reference(reason: :unresolved_job_reference,
344
- source: object.to_s,
345
- output_address: record[:output_address],
346
- evidence_address: record[:evidence_address],
347
- call_id: record[:call_id],
348
- tool_name: record[:tool_name],
349
- 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)
350
218
  end
351
219
  rescue StandardError => error
352
- provenance_error(on_error, error, :chat, object, :agent_job,
353
- agent_meta_error_reference(reason: :unresolved_job_reference,
354
- source: object.to_s,
355
- reference: reference,
356
- call_id: record[:call_id],
357
- 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)
358
224
  end
359
225
  end
360
226
  end
361
227
 
362
228
  if relations.include?(:log)
363
- # A saved chat owns its .files sidecar logs (society
364
- # conversations) just like a job owns its job logs.
365
229
  direct_chat_sidecar_files(object).each do |file|
366
- queue << [:chat, file, :chat, object, :log]
230
+ queue << [:chat, file, :chat, object, :log, nil]
367
231
  end
368
232
  end
369
233
  else
370
234
  if relations.include?(:dependency)
371
235
  object.dependencies.each do |dependency|
372
- queue << [:job, dependency, :job, object, :dependency]
236
+ queue << [:job, dependency, :job, object, :dependency, nil]
373
237
  end
374
238
  end
375
-
376
239
  if relations.include?(:log)
377
240
  direct_job_chat_files(object).each do |file|
378
- queue << [:chat, file, :job, object, :log]
241
+ queue << [:chat, file, :job, object, :log, nil]
379
242
  end
380
243
  end
381
-
382
244
  if relations.include?(:result) && (file = job_result_chat_file(object))
383
- queue << [:chat, file, :job, object, :result]
245
+ queue << [:chat, file, :job, object, :result, nil]
384
246
  end
385
247
  end
386
248
  rescue StandardError => error
387
249
  provenance_error(on_error, error, kind, object, relation, object)
388
250
  end
389
251
  end
390
-
391
252
  nil
392
253
  end
393
254
 
394
- # Flat structural edges suitable for JSON reports and renderers. Objects are
395
- # intentionally retained as native values; presentation code can shorten or
396
- # 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).
397
257
  #
398
- # `:agent_job` edges carry the agent_meta receipt record that produced them
399
- # under `detail:` (call id, tool name, output address, receipt address, job
400
- # reference). Two distinct receipts pointing at the same job therefore remain
401
- # two distinguishable edges instead of collapsing into one; ordinary edges
402
- # keep `detail: nil`.
403
- def self.provenance_edges(root, **options)
404
- edges = []
405
- traverse_provenance(root, **options) do |kind, object, parent_kind, parent, relation, _first, detail|
406
- next unless parent
407
- edge = {
408
- from_kind: parent_kind,
409
- from: parent,
410
- relation: relation,
411
- to_kind: kind,
412
- to: object,
413
- detail: detail
414
- }
415
- same_edge = lambda do |other|
416
- other[:relation] == relation &&
417
- provenance_key(other[:from_kind], other[:from]) == provenance_key(parent_kind, parent) &&
418
- provenance_key(other[:to_kind], other[:to]) == provenance_key(kind, object) &&
419
- (relation != :agent_job ||
420
- (detail.nil? && other[:detail].nil?) ||
421
- (detail && other[:detail] && detail[:evidence_address] == other[:detail][:evidence_address]))
422
- end
423
- edges << edge unless edges.any?(&same_edge)
424
- end
425
- edges
426
- end
427
-
428
- def self.provenance_chat_files(root, **options)
429
- files = []
430
- traverse_provenance(root, **options) do |kind, object, _pk, _parent, _relation, first|
431
- files << provenance_path(kind, object) if first && kind == :chat
432
- end
433
- files
434
- end
435
-
436
- def self.provenance_jobs(root, **options)
437
- jobs = []
438
- traverse_provenance(root, **options) do |kind, object, _pk, _parent, _relation, first|
439
- 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)
440
284
  end
441
- jobs
442
- end
443
-
444
- # Compatibility collector for the former chat-to-chat provenance Hash. New
445
- # code should use traverse_provenance or provenance_edges, which retain job
446
- # nodes and relation types.
447
- def self.provenance(chat_file, prov = {})
448
- traverse_provenance(chat_file) do |kind, object, parent_kind, parent, _relation, _first|
449
- next unless parent && kind == :chat
450
- parent_path = provenance_path(parent_kind, parent)
451
- prov[parent_path] ||= []
452
- path = provenance_path(kind, object)
453
- 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)
454
300
  end
455
- prov
456
- end
457
301
 
458
- # ------------------------------------------------------------------
459
- # Provenance-aware token accounting
460
- # ------------------------------------------------------------------
461
-
462
- # Canonical-evidence rule for grouped token events, applied in this order:
463
- #
464
- # 1. prefer :chat_meta evidence over :agent_meta evidence (a saved child
465
- # log chat is the richer, primary representation of the same request);
466
- # 2. within the same origin, the first evidence in discovery order
467
- # (provenance_chat_files order, then message index, then receipt
468
- # index).
469
- #
470
- # Event tokens always come from the canonical evidence only. Duplicate
471
- # evidence records are retained (never summed), so a total can always be
472
- # explained from the evidence list.
473
-
474
- # One event Hash per deduplicated direct inference event reachable from
475
- # `root`. A `job=` projection meta is never a token event, and only
476
- # evidence carrying at least one TOKEN_KEYS field becomes an event.
477
- #
478
- # Warning routing: when the caller supplies a `warnings` Array, two kinds of
479
- # problems are reported into it instead of raising:
480
- # * traversal-stage agent_meta problems (malformed receipts and unresolved
481
- # job references) arrive as the agent_meta_error_reference Hash plus
482
- # `message:`; the traversal keeps going so one bad receipt never hides
483
- # the rest of the provenance;
484
- # * identity_conflict records (see below).
485
- # Unrelated traversal errors keep strict semantics: they raise, both with and
486
- # without a warnings Array. Without the Array, agent_meta problems raise
487
- # exactly like Chat.traverse_provenance strict mode.
488
- #
489
- # Identity conflicts never raise here; pass `strict: true` to make them
490
- # raise instead of being reported (see below).
491
- #
492
- # Event shape:
493
- #
494
- # {
495
- # inference_id: <String or nil>,
496
- # identity: <the Array used for grouping, e.g. [:inference_id, "w1"]>,
497
- # deduplication: :inference_id | :provider_response_id |
498
- # :legacy_lineage | :receipt_unresolved,
499
- # meta: <canonical parsed meta>,
500
- # tokens: {pt:, ct:, tt:, cct:, cwt:, rt:} (symbols, zero-filled,
501
- # canonical evidence only),
502
- # evidence: [
503
- # {origin: :chat_meta, source:, meta_address:, meta:, call_id: nil,
504
- # tool_name: nil},
505
- # {origin: :agent_meta, source:, evidence_address:, output_address:,
506
- # agent_meta_index:, call_id:, tool_name:, meta:}
507
- # ],
508
- # conflict: true|false,
509
- # incomplete_evidence: true|false
510
- # }
511
- #
512
- # `evidence` holds EVERY persisted location of the event (the same
513
- # inference copied into several saved chats/logs appears once per chat plus
514
- # once per receipt). Only the canonical evidence supplies `meta` and
515
- # `tokens`.
516
- #
517
- # Identity (grouping) rules, in priority order:
518
- #
519
- # * meta[:inference_id] -> [:inference_id, id]
520
- # * meta[:provider_response_id] otherwise -> [:provider_response_id, id]
521
- # * chat-side legacy (neither) -> [:lineage, lineage_id], the
522
- # existing global lineage dedup of Chat.trace_chat_sources is preserved
523
- # * receipt-side legacy (neither) -> [:receipt, evidence_address];
524
- # there is no exact rule, so a receipt legacy meta is never merged with
525
- # anything (documented possible overcount for legacy data)
526
- #
527
- # Identity conflicts: when evidence sharing an identity disagree on any
528
- # TOKEN_KEYS value (compared as integers, missing counts as 0) or on
529
- # provider_response_id (two DIFFERENT non-empty values), the event keeps
530
- # every evidence record, counts only the canonical one, sets conflict: true,
531
- # and - when a warnings Array was supplied - appends one Hash per conflicting
532
- # event:
533
- #
534
- # {reason: :identity_conflict, inference_id:, identity:,
535
- # fields: <Array of disputed field symbols>,
536
- # values: <Hash field => the raw meta values in evidence order>,
537
- # evidence: <the event evidence records>}
538
- #
539
- # A missing provider_response_id in one record and a present one in another
540
- # is INCOMPLETE EVIDENCE, not a conflict: one copy simply carries richer
541
- # metadata (e.g. across a metadata-format migration). Such events set
542
- # incomplete_evidence: true, are counted normally, and are never warned about
543
- # as conflicts. The same leniency applies to optional detailed usage fields
544
- # (cct/cwt/rt): only the immutable core (inference identity, pt/ct/tt,
545
- # non-empty provider_response_id) can conflict.
546
- #
547
- # A conflicting event is counted once from its canonical evidence, but that
548
- # number is NOT authoritative: reports must label any total containing
549
- # conflicts as unresolved (see Chat.provenance_token_totals `conflicts:`).
550
- # Pass `strict: true` to raise ScoutException on the first conflict instead.
551
- #
552
- # Checkpoint fields (*_c, *_s) are never read or summed here.
553
- def self.provenance_token_events(root, warnings: nil, strict: false, **traversal_options)
554
- unless Thread.current[:scout_ai_provenance_run_cache]
555
- return with_provenance_run_cache do
556
- provenance_token_events(root, warnings: warnings, strict: strict, **traversal_options)
557
- end
558
- end
559
- # Route traversal-stage agent_meta problems into the caller's warnings
560
- # Array instead of letting them raise. Other traversal errors stay strict
561
- # (raise), and an explicitly supplied on_error keeps being called.
562
- if Array === warnings
563
- caller_on_error = traversal_options[:on_error]
564
- traversal_options = traversal_options.merge(
565
- on_error: lambda do |error, kind, object, relation, reference|
566
- if relation == :agent_job && reference.is_a?(Hash) && reference[:reason] &&
567
- error.message.to_s.include?('agent_meta receipt')
568
- warnings << reference.merge(message: error.message)
569
- caller_on_error.call(error, kind, object, relation, reference) if caller_on_error
570
- elsif caller_on_error
571
- 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))
572
326
  else
573
- 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)
574
330
  end
331
+ rescue StandardError => error
332
+ provenance_error(callback, error, :chat, transcript, :job, job_ref)
575
333
  end
576
- )
577
- end
578
-
579
- files = provenance_chat_files(root, **traversal_options)
580
- sources = {}
581
- files.each { |file| sources[file] = provenance_chat_load(file) }
582
-
583
- evidences = []
584
-
585
- # Chat-side direct events. `deduplicate: false` keeps one entry per
586
- # persisted location: an inference copied into several saved chats/logs
587
- # (or projected into several places) yields several evidence records, one
588
- # per address. Grouping by identity happens exactly once, below, so the
589
- # resulting event can list every location.
590
- trace_chat_sources(sources, false).each do |entry|
591
- meta = entry[:meta]
592
- next if meta[:job]
593
- next unless TOKEN_KEYS.any? { |key| meta.include?(key) }
594
- address = entry[:meta_address]
595
- evidences << {
596
- origin: :chat_meta,
597
- discovery: evidences.length,
598
- source: address ? address[0] : nil,
599
- meta_address: address,
600
- meta: meta,
601
- call_id: nil,
602
- tool_name: nil,
603
- inference_id: entry[:inference_id],
604
- lineage_id: entry[:lineage_id]
605
- }
606
- end
607
-
608
- # Receipt-side direct events. Malformed receipts are reported through a
609
- # private buffer and merged into the caller's warnings Array only when the
610
- # traversal stage has not already reported the same problem (it reports
611
- # with the richer reference + message shape whenever :agent_job is
612
- # followed); without an Array, agent_meta_evidence skips them silently.
613
- receipt_problems = Array === warnings ? [] : nil
614
- sources.each do |path, chat|
615
- agent_meta_evidence(chat, source: path, warnings: receipt_problems).each do |record|
616
- meta = record[:meta]
617
- next if meta[:job]
618
- next unless TOKEN_KEYS.any? { |key| meta.include?(key) }
619
- evidences << {
620
- origin: :agent_meta,
621
- discovery: evidences.length,
622
- source: path,
623
- evidence_address: record[:evidence_address],
624
- output_address: record[:output_address],
625
- agent_meta_index: record[:agent_meta_index],
626
- meta: meta,
627
- call_id: record[:call_id],
628
- tool_name: record[:tool_name],
629
- inference_id: meta[:inference_id],
630
- lineage_id: nil
631
- }
632
- end
633
- end
634
-
635
- if receipt_problems && !receipt_problems.empty?
636
- reported = Set.new(warnings.collect do |warning|
637
- next if warning[:reason] == :identity_conflict
638
- [warning[:reason], warning[:output_address], warning[:agent_meta_index]]
639
- end)
640
- receipt_problems.each do |problem|
641
- key = [problem[:reason], problem[:output_address], problem[:agent_meta_index]]
642
- warnings << problem unless reported.include?(key)
643
- end
644
- end
645
-
646
- origin_rank = { chat_meta: 0, agent_meta: 1 }
647
- events = []
648
- by_identity = {}
649
-
650
- evidences.each do |evidence|
651
- meta = evidence[:meta]
652
- if evidence[:inference_id]
653
- identity = [:inference_id, evidence[:inference_id]]
654
- deduplication = :inference_id
655
- elsif meta[:provider_response_id]
656
- identity = [:provider_response_id, meta[:provider_response_id]]
657
- deduplication = :provider_response_id
658
- elsif evidence[:origin] == :chat_meta
659
- identity = [:lineage, evidence[:lineage_id]]
660
- deduplication = :legacy_lineage
661
- else
662
- identity = [:receipt, evidence[:evidence_address]]
663
- deduplication = :receipt_unresolved
664
- end
665
-
666
- event = by_identity[identity]
667
- unless event
668
- event = { identity: identity, deduplication: deduplication, _evidence: [] }
669
- by_identity[identity] = event
670
- events << event
671
334
  end
672
- event[:_evidence] << evidence
673
- end
674
335
 
675
- events.each do |event|
676
- ordered = event.delete(:_evidence).sort_by do |evidence|
677
- [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 = []
678
345
  end
679
- canonical = ordered.first
680
-
681
- event[:evidence] = ordered.collect do |evidence|
682
- record = {
683
- origin: evidence[:origin],
684
- source: evidence[:source],
685
- meta: evidence[:meta],
686
- call_id: evidence[:call_id],
687
- tool_name: evidence[:tool_name]
688
- }
689
- if evidence[:origin] == :chat_meta
690
- record[:meta_address] = evidence[:meta_address]
691
- else
692
- record[:evidence_address] = evidence[:evidence_address]
693
- record[:output_address] = evidence[:output_address]
694
- 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)
695
361
  end
696
- record
697
362
  end
698
363
 
699
- event[:inference_id] = canonical[:inference_id]
700
- event[:meta] = canonical[:meta]
701
- event[:tokens] = TOKEN_KEYS.each_with_object({}) do |key, hash|
702
- hash[key.to_sym] = canonical[:meta][key].to_i
703
- end
704
-
705
- # Immutable core only: pt/ct/tt and a genuinely different non-empty
706
- # provider_response_id. Optional detail fields (cct, cwt, rt) and a
707
- # missing-vs-present provider_response_id are incomplete evidence, not
708
- # conflicts.
709
- core_fields = %i[pt ct tt]
710
- fields = []
711
- values = {}
712
- core_fields.each do |key|
713
- next unless ordered.collect { |evidence| evidence[:meta][key].to_i }.uniq.length > 1
714
- fields << key
715
- values[key] = ordered.collect { |evidence| evidence[:meta][key] }
716
- end
717
- provider_ids = ordered.collect { |evidence| evidence[:meta][:provider_response_id].to_s }
718
- .reject { |value| value.strip.empty? }.uniq
719
- if provider_ids.length > 1
720
- fields << :provider_response_id
721
- 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)
722
379
  end
380
+ end
381
+ receipt_warnings.each { |warning| warnings << {kind: :agent_meta, warning: warning} }
723
382
 
724
- # Incomplete evidence: exactly one non-empty provider_response_id value
725
- # while at least one copy lacks it (metadata-format migration), so there
726
- # is nothing to disagree about.
727
- present_ids = ordered.collect { |evidence| evidence[:meta][:provider_response_id].to_s }
728
- .reject { |value| value.strip.empty? }
729
- if present_ids.uniq.length <= 1 &&
730
- present_ids.length != ordered.length && !present_ids.empty?
731
- 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)
732
391
  end
392
+ end
733
393
 
734
- next unless fields.any?
735
- event[:conflict] = true
736
- if strict
737
- raise ScoutException, "agent_meta identity conflict on #{event[:identity] * '='}: disputed #{fields * ','}"
738
- end
739
- next unless Array === warnings
740
- warnings << {
741
- reason: :identity_conflict,
742
- inference_id: event[:inference_id],
743
- identity: event[:identity],
744
- fields: fields,
745
- values: values,
746
- evidence: event[:evidence]
747
- }
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
+ []
748
400
  end
749
401
 
750
- # Reorder keys readably; conflict defaults to false.
751
- events.collect do |event|
752
- {
753
- inference_id: event[:inference_id],
754
- identity: event[:identity],
755
- deduplication: event[:deduplication],
756
- meta: event[:meta],
757
- tokens: event[:tokens],
758
- evidence: event[:evidence],
759
- conflict: event[:conflict] || false,
760
- incomplete_evidence: event[:incomplete_evidence] || false
761
- }
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]
762
415
  end
763
416
  end
764
417
 
765
- # Aggregate token totals over deduplicated provenance events. The result is
766
- # symbol keyed and zero initialized exactly like Chat.token_totals:
767
- # {pt:, ct:, tt:, cct:, cwt:, rt:}.
768
- #
769
- # Scopes. These are EVIDENCE COVERAGE descriptions, not a partition of cost:
770
- # an event represented both in a saved child log and in a receipt belongs to
771
- # :chat_evidence AND to :receipt_evidence, so the two are not additive and
772
- # must never be summed together. Only :deduplicated_total and :receipt_only
773
- # are safe to compare additively.
774
- #
775
- # * :deduplicated_total - every event counted once (default);
776
- # * :chat_evidence - events with at least one :chat_meta evidence
777
- # (physically stored in a chat/log file);
778
- # * :receipt_evidence - events with at least one :agent_meta evidence
779
- # (embedded in a function_call_output receipt);
780
- # * :receipt_only - events with receipt evidence and NO saved-chat
781
- # evidence (the disjoint delegated contribution).
782
- #
783
- # Conflict handling: a conflicting event still contributes its canonical
784
- # tokens, so a total containing conflicts is a best-effort view, not an
785
- # authoritative cost. The `conflicts:` keyword makes that explicit in
786
- # machine readable form; with `strict: true` conflicts raise instead (the
787
- # keyword is forwarded to provenance_token_events).
788
- def self.provenance_token_totals(root, scope: :deduplicated_total, warnings: nil,
789
- conflicts: nil, **traversal_options)
790
- events = provenance_token_events(root, warnings: warnings, **traversal_options)
791
-
792
- selected = case scope.to_sym
793
- when :deduplicated_total
794
- events
795
- when :chat_evidence
796
- events.select { |event| event[:evidence].any? { |e| e[:origin] == :chat_meta } }
797
- when :receipt_evidence
798
- events.select { |event| event[:evidence].any? { |e| e[:origin] == :agent_meta } }
799
- when :receipt_only
800
- events.select do |event|
801
- event[:evidence].any? { |e| e[:origin] == :agent_meta } &&
802
- 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)
803
430
  end
804
431
  else
805
- 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
806
435
  end
807
436
 
808
- totals = TOKEN_KEYS.each_with_object({}) { |key, hash| hash[key.to_sym] = 0 }
809
- selected.each do |event|
810
- TOKEN_KEYS.each { |key| totals[key.to_sym] += event[:tokens][key.to_sym] }
811
- 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)
812
459
 
813
- if conflicts.is_a?(Hash)
814
- conflicting = events.select { |event| event[:conflict] }
815
- incomplete = events.select { |event| event[:incomplete_evidence] }
816
- conflicts[:events] = conflicting.length
817
- conflicts[:incomplete_evidence_events] = incomplete.length
818
- conflicts[:authoritative] = conflicting.empty?
460
+ edges << {from_kind: parent_kind, from: parent, relation: relation,
461
+ to_kind: kind, to: object, detail: detail}
819
462
  end
820
463
 
821
- totals
464
+ {root_kind: resolved_kind, root: resolved_root, chats: chats,
465
+ jobs: jobs, edges: edges, warnings: warnings}
822
466
  end
823
467
 
824
- # Provenance token aggregate. Receipt (agent_meta) child usage is now
825
- # included through the event collector, so child inference paid inside a
826
- # parent tool call is no longer invisible when the child chat was not saved.
827
- def self.tokens(root, **options)
828
- provenance_token_totals(root, **options)
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}
829
471
  end
830
472
 
831
- def self.timestamp
832
- Time.now.utc.iso8601(3)
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]
477
+ end
478
+
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
833
497
  end
834
498
  end
499
+
500
+ require_relative 'provenance/tokens'
501
+ require_relative 'provenance/live'