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
@@ -0,0 +1,1080 @@
1
+ # Extracted from the existing live-workload implementation.
2
+ module Chat
3
+ # ------------------------------------------------------------------
4
+ # Live workload: the transient <base>.jobs sidecar
5
+ # ------------------------------------------------------------------
6
+ # `LLM.process_calls` writes the short paths of the workflow jobs it is
7
+ # currently producing (Workflow.produce blocking) to `Chat.jobs_file`,
8
+ # rewriting per round and removing the file in an `ensure` when produce
9
+ # returns. This section turns that transient snapshot into the LIVE view
10
+ # of an agent's workload, complementing the FORENSIC traversal above:
11
+ # absent file is a non-event, never an error.
12
+
13
+ # Terminal statuses as recorded in a job `.info` after Workflow.produce
14
+ # returns (or an abort/clean sweep). Anything else is in-flight or stale,
15
+ # decided by pid liveness below.
16
+ LIVE_TERMINAL_STATUSES = %w[done error aborted cleaned].freeze
17
+
18
+ # Is `pid` a live process right now? Mirrors Misc.pid_alive? but adds the
19
+ # zombie guard: a child that exited without being reaped still answers
20
+ # kill(0, 0), yet produces nothing, so a zombie is NOT running work.
21
+ def self.live_pid?(pid)
22
+ return false if pid.nil? || pid.to_s.empty?
23
+ pid = pid.to_i
24
+ return false unless pid > 0
25
+ return true if pid == Process.pid
26
+ stat = File.read("/proc/#{pid}/stat") rescue nil
27
+ return false if stat.nil?
28
+ # field 3 of /proc/<pid>/stat is the state; Z = zombie
29
+ state = stat.split(')')[-1].split[0]
30
+ state != 'Z'
31
+ rescue Errno::ENOENT, Errno::ESRCH
32
+ false
33
+ end
34
+
35
+ # Classify one in-flight workload entry from its `.info`:
36
+ # [:running, status] non-terminal status + live pid
37
+ # [:crashed, status] non-terminal status + dead/absent pid
38
+ # [:finished, status] terminal status (done/error/aborted/cleaned)
39
+ #
40
+ # Snapshot-contract caveats: `kill -9` leaves `.info` non-terminal forever
41
+ # (pid liveness is the only way to distinguish running from crashed, and
42
+ # the LocalExecutor retry can RESURRECT such a job by overwriting `.info`
43
+ # with a new pid, so a :crashed verdict is valid only for the moment it
44
+ # was computed); a listed job may complete between reading `<base>.jobs`
45
+ # and its `.info` (the classification reports what was seen); a missing
46
+ # `.info` reports :crashed with a nil status.
47
+ def self.classify_live_job(step)
48
+ info = begin
49
+ step.info
50
+ rescue StandardError
51
+ nil
52
+ end
53
+ return [:crashed, nil] unless Hash === info
54
+
55
+ state, status = classify_live_job_info(info)
56
+ # classify_live_job_info returns the raw status value; this reader has
57
+ # always reported it as a String, so normalize without changing any
58
+ # observable verdict.
59
+ [state, status.to_s]
60
+ end
61
+
62
+ # Resolve one short-path entry of the live sidecar to a Step.
63
+ #
64
+ # The Workflow jobs tree root (`Workflow.directory`) is tried FIRST because
65
+ # that is where process_calls actually produced the job: the sidecar stores
66
+ # SHORT paths, and Step.load rewrites a bare short path through
67
+ # Path.find/Step.relocate, which can land on a different (empty) mirror of
68
+ # the tree (e.g. `~/.scout/var/jobs/...` while the real job lives under the
69
+ # run's Workflow.directory). Falling back to the forensic
70
+ # `load_job_reference` chain keeps unresolved entries diagnosable.
71
+ def self.load_live_job_reference(reference)
72
+ return reference if Step === reference
73
+ ref_str = reference.to_s
74
+
75
+ base = Workflow.directory.respond_to?(:find) ? Workflow.directory.find : Workflow.directory
76
+ candidate = File.join(base.to_s, ref_str)
77
+ return Step.load(candidate) if job_reference_candidate?(candidate)
78
+
79
+ step = Step.load(ref_str)
80
+ return step if job_reference_candidate?(step.path.to_s)
81
+
82
+ load_job_reference(ref_str)
83
+ end
84
+
85
+ # Resolve each entry of the live sidecar of `save_file` (or the chat/job
86
+ # path it stands for) into a Step with its live classification. Returns an
87
+ # Array of Hashes (one per sidecar entry, order preserved):
88
+ #
89
+ # {reference: 'WF/task/name', step: Step, path: <job dir>,
90
+ # status: 'running'|..., state: :running/:crashed/:finished,
91
+ # chat_task: true|false}
92
+ #
93
+ # `chat_task` uses the LIVE discriminator `step.type.to_s == 'chat'`
94
+ # (chat_task annotation; a hand-written task declaring :chat is inference
95
+ # by definition). The CONCLUDED discriminator (output JSON with exactly
96
+ # `meta` and `content` keys) belongs to the forensic traversal and is NOT
97
+ # re-checked here: the sidecar only ever lists in-flight jobs. An
98
+ # absent sidecar is a NON-EVENT: []. Resolution uses the same
99
+ # fallback chain as forensic job references (`load_job_reference`), so a
100
+ # short path resolves against the workflow jobs tree.
101
+ def self.live_workload(reference)
102
+ base = reference.respond_to?(:path) ? reference.path.to_s : reference.to_s
103
+
104
+ # Accept a chat file, a job path (result chat) or a bare save_file: the
105
+ # sidecar is always derived from the save_file base via Chat.jobs_file.
106
+ candidates = [base, base.sub(/\.chat\z/, '')]
107
+ sidecar = candidates.collect { |c| Chat.jobs_file(c) }
108
+ .find { |f| File.exist?(f) }
109
+
110
+ return [] if sidecar.nil?
111
+
112
+ entries = Open.read(sidecar).split("\n")
113
+ .collect(&:strip).reject(&:empty?)
114
+
115
+ entries.collect do |entry|
116
+ step = load_live_job_reference(entry)
117
+ state, status = classify_live_job(step)
118
+ type = begin
119
+ step.type.to_s
120
+ rescue
121
+ nil
122
+ end
123
+ {
124
+ reference: entry,
125
+ step: step,
126
+ path: step.path.to_s,
127
+ status: status,
128
+ state: state,
129
+ chat_task: type == 'chat'
130
+ }
131
+ end
132
+ end
133
+
134
+ # ------------------------------------------------------------------
135
+ # Dependency expansion + unified live report
136
+ # ------------------------------------------------------------------
137
+ # expand_live_jobs below walks the dependencies a wrapper job RECORDS in
138
+ # its `.info`; live_report folds the three live passes. Between them
139
+ # sits one repair: the waiting-wrapper fallback.
140
+
141
+ # ------------------------------------------------------------------
142
+ # Waiting-wrapper fallback: definition-blind dependency discovery
143
+ # ------------------------------------------------------------------
144
+ # A wrapper job whose chat_task dependency is still running sits at
145
+ # `{"status":"waiting"}` with NO pid and NO `dependencies` key:
146
+ # scout-gear's Step#run records the dependency list in `.info` only at
147
+ # reset_info(status: :setup) inside the persist block, i.e. AFTER
148
+ # run_dependencies returns — a file-based reader that only consults
149
+ # `step.dependencies` is structurally blind in exactly the window the
150
+ # live pass exists for. Fallback: running sibling job directories in
151
+ # the wrapper's own WORKFLOW namespace (`var/jobs/<Workflow>/<task>`,
152
+ # where scout-gear materializes every dependency). The workflow
153
+ # definition is deliberately NOT loaded (require_workflow resolves
154
+ # names through the `workflows` pathmap, which cannot see an arbitrary
155
+ # jobs tree); only jobs in the same workflow directory are considered,
156
+ # and captured ids keep their dedup role.
157
+
158
+ # Candidate dependency jobs of a wrapper Step whose `.info` predates
159
+ # dependency recording: running sibling job directories in the wrapper's
160
+ # WORKFLOW namespace — where scout-gear materializes every dependency of
161
+ # the wrapper. Returns [] when the step is fine (has recorded
162
+ # dependencies), is in a terminal phase, or nothing on disk qualifies.
163
+ # Never raises.
164
+ def self.live_dependency_candidates(step)
165
+ return [] unless Step === step
166
+ info = begin
167
+ step.info
168
+ rescue StandardError
169
+ return []
170
+ end
171
+ return [] if Array === info[:dependencies] && !info[:dependencies].empty?
172
+
173
+ status = info[:status].to_s
174
+ return [] if LIVE_TERMINAL_STATUSES.include?(status)
175
+
176
+ # Workflow namespace, one level ABOVE the wrapper's task dir:
177
+ # dependencies materialize as sibling TASK directories under
178
+ # var/jobs/<Workflow>/ (CortexWF/continue beside
179
+ # CortexWF/cortex_continue), never inside the wrapper's own task dir.
180
+ workflow_dir = begin
181
+ File.dirname(File.dirname(step.path.to_s))
182
+ rescue StandardError
183
+ return []
184
+ end
185
+ return [] unless File.directory?(workflow_dir)
186
+
187
+ step_path = step.path.to_s
188
+ candidates = []
189
+ # Glob `.info` files, not job directories: a chat_task's job path is
190
+ # itself a FILE (`<name>.chat`, the result), with `.files` beside it;
191
+ # a directory-only scan sees `<name>.chat.files` and misses the job.
192
+ Dir.glob(File.join(workflow_dir, '*', '*.info')).sort.each do |info_file|
193
+ entry = info_file.sub(/\.info\z/, '')
194
+ next if entry == step_path
195
+
196
+ begin
197
+ dep_info = Step.load_info(info_file)
198
+ rescue StandardError
199
+ next
200
+ end
201
+ state, _status = classify_live_job_info(dep_info)
202
+ next unless state == :running
203
+
204
+ dep_step = begin
205
+ Step.load(entry)
206
+ rescue StandardError
207
+ next
208
+ end
209
+ candidates << dep_step
210
+ end
211
+ candidates
212
+ end
213
+
214
+ # Same classification as classify_live_job but from an already-loaded
215
+ # info Hash (no Step round-trip); used by live_dependency_candidates.
216
+ def self.classify_live_job_info(info)
217
+ return [:unknown, nil] unless Hash === info
218
+ status = info[:status]
219
+ if LIVE_TERMINAL_STATUSES.include?(status.to_s)
220
+ return [:finished, status]
221
+ end
222
+ state = live_pid?(info[:pid]) ? :running : :crashed
223
+ [state, status]
224
+ end
225
+
226
+ # ------------------------------------------------------------------
227
+ # Unified live report: sidecar + agent view + society, deduplicated
228
+ # ------------------------------------------------------------------
229
+ # The `.jobs` sidecar lists the job the tool call RESOLVED (a plain
230
+ # wrapper such as Cortex#cortex_continue), while the actually-running
231
+ # inference lives in a DEPENDENCY job (the chat task Cortex#continue)
232
+ # whose `.info` LLM.process_calls has already inited (tools/call.rb):
233
+ # the dependency chain is exactly where the live inference is; the
234
+ # sidecar entry alone is not. live_report below folds the three live
235
+ # passes into the one data-only report the CLI renders.
236
+
237
+ # Depth cap for the dependency walk. Step#rec_dependencies is itself
238
+ # cycle-safe (it threads a seen-set through the recursion, scout-gear
239
+ # lib/scout/workflow/step/dependencies.rb), so this cap is a second,
240
+ # independent guard against a hand-built or stubbed dependency graph and
241
+ # against pathological depth; it is not load-bearing for real graphs.
242
+ LIVE_DEPENDENCY_DEPTH_LIMIT = 5
243
+
244
+ # Agent log file of a running chat task: the chat_task machinery anchors
245
+ # its agents under the JOB's files dir (AgentWorkflow log_agent,
246
+ # agent/workflow.rb: `agent.save_file = Agent.canonical_chat_file(
247
+ # files_dir, agent_name)`), so the log lives at
248
+ # `<job>.files/<agent_name>.chat` and defaults to `agent.chat` when the
249
+ # agent was unnamed. Returns nil when no such file exists.
250
+ def self.live_chat_task_agent_log(step, agent_name: nil)
251
+ return nil unless Step === step
252
+ files_dir = begin
253
+ step.files_dir
254
+ rescue
255
+ return nil
256
+ end
257
+ return nil if files_dir.nil?
258
+
259
+ names = agent_name ? [agent_name] : ['agent', nil]
260
+ names.each do |name|
261
+ begin
262
+ candidate = LLM::Agent.canonical_chat_file(files_dir, name)
263
+ rescue
264
+ return nil
265
+ end
266
+ return candidate if File.exist?(candidate)
267
+ end
268
+
269
+ nil
270
+ end
271
+
272
+ # Expand sidecar job entries into the set of RUNNING jobs reachable from
273
+ # them (each entry plus its dependencies), with cycle (visited-set) and
274
+ # depth (LIVE_DEPENDENCY_DEPTH_LIMIT) guards. Returns an Array of
275
+ # Hashes:
276
+ #
277
+ # {step: Step, path:, reference:, status:, state: :running,
278
+ # chat_task: true|false, agent_log: <path or nil>,
279
+ # activity: <agent_log_activity hash or nil>,
280
+ # via: <short path of the sidecar entry that reached it>}
281
+ #
282
+ # Only `classify_live_job == :running` jobs are kept (finished/crashed
283
+ # dependencies are not live work); running non-chat dependencies stay
284
+ # as workload CONTEXT (the unified report separates inference from
285
+ # context, this method keeps both), and `via` records which sidecar
286
+ # entry each job was reached through, so the wrapper's presence stays
287
+ # visible without duplicating the inference.
288
+ def self.expand_live_jobs(entries)
289
+ entries = entries.respond_to?(:each) ? entries : [entries]
290
+ collected = []
291
+ visited = Set.new
292
+
293
+ entries.each do |entry|
294
+ step = Step === entry ? entry : load_live_job_reference(entry)
295
+ # `via` is the sidecar ENTRY (short path) for a String entry, or the
296
+ # job's own short path for a Step entry, so the reported `reference`
297
+ # stays in the same form the sidecar and a `job=` meta both use.
298
+ via = Step === entry ? begin
299
+ step.short_path
300
+ rescue StandardError
301
+ step.path.to_s
302
+ end : entry.to_s
303
+ walk_live_job(step, via, 0, visited, collected)
304
+ end
305
+
306
+ collected
307
+ end
308
+
309
+ # One visited node of the dependency walk: classify, keep if running,
310
+ # recurse into dependencies while under the depth cap. Fail-soft per
311
+ # job: an entry whose job cannot be loaded or classified is skipped
312
+ # silently (the forensic traversal is the place to diagnose it).
313
+ def self.walk_live_job(step, via, depth, visited, collected)
314
+ return nil unless Step === step
315
+
316
+ path = begin
317
+ step.path.to_s
318
+ rescue
319
+ return nil
320
+ end
321
+ return nil if visited.include?(path)
322
+ visited << path
323
+
324
+ state, status = classify_live_job(step)
325
+ if state == :running
326
+ type = begin
327
+ step.type.to_s
328
+ rescue
329
+ nil
330
+ end
331
+ chat_task = type == 'chat'
332
+ agent_log = chat_task ? live_chat_task_agent_log(step) : nil
333
+ reference = begin
334
+ step.short_path
335
+ rescue StandardError
336
+ via
337
+ end
338
+ collected << {
339
+ step: step,
340
+ path: path,
341
+ reference: reference,
342
+ status: status,
343
+ state: state,
344
+ chat_task: chat_task,
345
+ agent_log: agent_log,
346
+ activity: agent_log ? agent_log_activity(agent_log) : nil,
347
+ via: via
348
+ }
349
+ end
350
+
351
+ return nil if depth >= LIVE_DEPENDENCY_DEPTH_LIMIT
352
+
353
+ # One level at a time, NOT Step#rec_dependencies: rec_dependencies is
354
+ # itself a recursive, cycle-safe flattener, so walking it would return
355
+ # the whole transitive set on the first hop and make the depth cap
356
+ # below meaningless (it can never fire past depth one). Walking
357
+ # `dependencies` (the direct, recorded edges) keeps BOTH guards of this
358
+ # walk operative: the visited-set here and the depth cap, each an
359
+ # independent second line of defense for stubbed or hand-built graphs.
360
+ deps = begin
361
+ step.dependencies
362
+ rescue StandardError
363
+ []
364
+ end
365
+
366
+ # Waiting-wrapper repair (see the fallback section above): a wrapper in
367
+ # a pre-dependency phase (waiting, no `dependencies` key yet, no pid)
368
+ # records nothing for `step.dependencies` to walk — fall back to the
369
+ # definition-blind sibling scan of its task namespace. Only invoked
370
+ # when the recorded set is empty AND the step itself is in that phase,
371
+ # so a DONE wrapper or a genuinely dependency-free task is unaffected.
372
+ if Array(deps).empty?
373
+ candidates = live_dependency_candidates(step)
374
+ unless candidates.empty?
375
+ collected << {
376
+ step: step,
377
+ path: path,
378
+ reference: begin
379
+ step.short_path
380
+ rescue StandardError
381
+ via
382
+ end,
383
+ status: status,
384
+ state: :waiting,
385
+ chat_task: false,
386
+ agent_log: nil,
387
+ activity: nil,
388
+ via: via
389
+ }
390
+ end
391
+ deps = candidates
392
+ end
393
+ Array(deps).each do |dep|
394
+ walk_live_job(dep, via, depth + 1, visited, collected)
395
+ end
396
+ nil
397
+ end
398
+
399
+ # Merge two entries KNOWN to share one job identity (cross-pass: the
400
+ # sidecar pass and a dangling `job=` meta naming the same job). Keys
401
+ # present in only one entry win as-is; keys present in both resolve to
402
+ # the non-nil/non-empty side; :source tags union. Job-derived fields
403
+ # therefore keep the richest view, never two entries for one job. The
404
+ # per-agent-log kind/precedence rules live in
405
+ # reconcile_agent_log_entries, which calls this for same-identity
406
+ # entries ONLY — never across different references.
407
+ def self.merge_live_entries(one, other)
408
+ merged = one.dup
409
+ other.each do |key, value|
410
+ current = merged[key]
411
+ if current.nil? || current.respond_to?(:empty?) && current.empty?
412
+ merged[key] = value
413
+ elsif value.is_a?(Hash) && current.is_a?(Hash)
414
+ merged[key] = current.merge(value)
415
+ end
416
+ end
417
+ merged[:source] = [one[:source], other[:source]].flatten.compact.uniq if one[:source] || other[:source]
418
+ merged
419
+ end
420
+
421
+ # Reconcile ALL live entries of ONE agent log into the foldable list:
422
+ # one entry per distinct outstanding job reference, plus (only when the
423
+ # log has none) its bare activity entry. Explicit rules:
424
+ #
425
+ # 1. Identity: entries sharing a job reference combine into one
426
+ # entry keeping that identity and its job-derived fields (:state,
427
+ # :status, :path, :step).
428
+ # 2. DIFFERENT outstanding references never combine — each becomes
429
+ # its own entry carrying :references (its identity, deduplicated);
430
+ # no reference collapses to the first.
431
+ # 3. Kind precedence: when the log also has live activity, the merged
432
+ # kind is :dangling_job and the activity hash rides on the FIRST
433
+ # reference's entry (first-seen order in the log, independent of
434
+ # caller push order).
435
+ # 4. :source tags union through merge_live_entries.
436
+ #
437
+ # Accepts either producer shape: agent_view_live's per-reference
438
+ # dangling entries, and society_live's single entry carrying :job plus
439
+ # every reference in :dangling (expanded to one entry per reference,
440
+ # so society children get the same rule 2 guarantee).
441
+ def self.reconcile_agent_log_entries(entries)
442
+ danglings = []
443
+ activity = nil
444
+ others = []
445
+ entries.each do |entry|
446
+ case entry[:kind]
447
+ when :dangling_job
448
+ refs = Array === entry[:dangling] && !entry[:dangling].empty? ? entry[:dangling] : [entry]
449
+ danglings.concat(refs)
450
+ when :agent_activity
451
+ activity ||= entry
452
+ else
453
+ others << entry
454
+ end
455
+ end
456
+
457
+ return others + (activity ? [activity] : []) if danglings.empty?
458
+
459
+ # Group same-identity references (first-seen order).
460
+ groups = {}
461
+ order = []
462
+ danglings.each do |entry|
463
+ id = entry[:reference].to_s
464
+ id = entry[:job].to_s if id.empty?
465
+ id = entry[:path].to_s if id.empty?
466
+ next if id.empty?
467
+ order << id unless groups.key?(id)
468
+ (groups[id] ||= []) << entry
469
+ end
470
+
471
+ order.each_with_index.collect do |id, index|
472
+ group = groups[id]
473
+ merged = group.first.dup
474
+ group.drop(1).each { |entry| merged = merge_live_entries(merged, entry) }
475
+ merged[:reference] = id
476
+ merged[:references] = [id]
477
+ if index.zero? && activity
478
+ merged = merge_live_entries(merged,
479
+ activity.reject { |key, _| key == :kind })
480
+ merged[:kind] = :dangling_job
481
+ merged[:activity] = activity
482
+ .reject { |key, _| %i(kind agent_file).include?(key) }
483
+ end
484
+ merged
485
+ end
486
+ end
487
+
488
+ # Unified LIVE report for the chat (or job) at `save_file`/`reference`,
489
+ # the single data-only unit that folds the three live passes and that
490
+ # the CLI renders.
491
+ #
492
+ # Chat.live_report(save_file, captured: ids)
493
+ # # => {entries: [...], scanned: {sidecar: bool, agent_view: bool,
494
+ # # society: bool}}
495
+ #
496
+ # Entry schema (superset per kind; kind is one of :inference,
497
+ # :workload_context, :agent_activity, :dangling_job):
498
+ #
499
+ # {kind:, source: [:sidecar|:agent_view|:society|...],
500
+ # reference:, path:, state:, status:, chat_task:,
501
+ # agent_log:, activity:, agent:, conversation:, via:, parent:}
502
+ #
503
+ # Folding and dedup rules:
504
+ # * entries whose job id is in `captured` (live_captured_ids) are
505
+ # dropped in EVERY pass: the forensic main report already holds them;
506
+ # * cross-pass dedup is by job id (reference/path), merging facts
507
+ # (merge_live_entries), never emitting two entries for one job;
508
+ # * per agent-log file the entries are reconciled by
509
+ # reconcile_agent_log_entries: one entry per DISTINCT outstanding
510
+ # job reference (never collapsed to the first), and when the log
511
+ # also has live activity the dangling job wins as the kind with the
512
+ # activity hash riding on the first reference's entry;
513
+ # * a running sidecar job that is a chat task becomes an :inference
514
+ # entry; a running non-chat job becomes :workload_context (the plain
515
+ # information live_workload already reported must not disappear).
516
+ #
517
+ # Everything is fail-soft: absent sidecar, absent agent save file, absent
518
+ # society tree and unreadable jobs each yield nothing and never raise.
519
+ def self.live_report(save_file, captured: [])
520
+ captured_ids = live_captured_ids(captured)
521
+ base = save_file.respond_to?(:path) ? save_file.path.to_s : save_file.to_s
522
+
523
+ # Entries are keyed by job id where one exists (the sidecar SHORT path,
524
+ # the same form a `job=` meta stores, so cross-pass matches are plain
525
+ # string equality) and by agent-log path otherwise.
526
+ entries = {}
527
+
528
+ # --- sidecar pass with dependency expansion ---
529
+ # `live_workload` keeps its contract (entries only); the expansion
530
+ # walks each entry plus its dependencies so the dependency job
531
+ # actually running the inference is reported, not just the wrapper
532
+ # the tool call resolved.
533
+ sidecar_entries = begin
534
+ expand_live_jobs(live_workload(base).collect { |e| e[:step] })
535
+ rescue StandardError
536
+ []
537
+ end
538
+ sidecar_entries.each do |entry|
539
+ job_id = entry[:reference].to_s
540
+ next if job_id.empty?
541
+ next if captured_ids.include?(job_id) ||
542
+ captured_ids.include?(entry[:path].to_s)
543
+
544
+ folded = entry.merge(kind: entry[:chat_task] ? :inference : :workload_context,
545
+ source: [:sidecar])
546
+ # A waiting wrapper surfaced only by the fallback is neither running
547
+ # inference nor finished: report it as workload context (it is live
548
+ # state — its dependency is running) instead of letting classify's
549
+ # :crashed verdict drop it.
550
+ if entry[:state] == :waiting && !entry[:chat_task]
551
+ folded = folded.merge(kind: :workload_context,
552
+ state: :waiting,
553
+ status: entry[:status])
554
+ end
555
+ entries[job_id] = entries.key?(job_id) ?
556
+ merge_live_entries(entries[job_id], folded) : folded
557
+ end
558
+ scanned_sidecar = begin
559
+ [base, base.sub(/\.chat\z/, '')].any? { |b| File.exist?(Chat.jobs_file(b)) }
560
+ rescue StandardError
561
+ false
562
+ end
563
+
564
+ # --- agent view pass on the root agent save file ---
565
+ agent_entries = begin
566
+ agent_view_live(base, captured: captured)
567
+ rescue StandardError
568
+ []
569
+ end
570
+
571
+ # --- society pass ---
572
+ society_entries = begin
573
+ society_live(base, captured: captured)
574
+ rescue StandardError
575
+ []
576
+ end
577
+
578
+ # Reconcile the live entries of each agent log (reconcile_agent_log_entries
579
+ # owns the per-log rules) and merge the result into the job-id space, so
580
+ # a job the sidecar already reported and a dangling `job=` meta name once.
581
+ agent_side = Hash.new { |hash, key| hash[key] = [] }
582
+ ([[:agent_view, agent_entries], [:society, society_entries]]).each do |source, list|
583
+ list.each do |entry|
584
+ log_file = entry[:agent_file] || entry[:path]
585
+ next if log_file.nil?
586
+
587
+ agent_side[log_file] << entry.merge(source: [source])
588
+ end
589
+ end
590
+
591
+ agent_side.each do |log_file, log_entries|
592
+ reconcile_agent_log_entries(log_entries).each do |entry|
593
+ # A log file whose RUNNING `job=` references were all captured has
594
+ # its liveness already represented by those jobs: drop the bare
595
+ # activity entry too (the same rule society_live applies to its
596
+ # children). Files with no running reference at all (the
597
+ # Clean-type gap) keep their activity entry.
598
+ if entry[:kind] == :agent_activity
599
+ running_refs = begin
600
+ live_chat_state(log_file)[:dangling]
601
+ rescue StandardError
602
+ []
603
+ end
604
+ next if !running_refs.empty? &&
605
+ running_refs.all? { |ref| captured_ids.include?(ref[:reference].to_s) }
606
+ end
607
+
608
+ job_id = entry[:reference].to_s
609
+ job_id = entry[:job].to_s if job_id.empty?
610
+ next if !job_id.empty? && (captured_ids.include?(job_id) ||
611
+ captured_ids.include?(entry[:path].to_s))
612
+
613
+ folded = entry.merge(source: [entry[:source]].flatten.compact.uniq)
614
+ if !job_id.empty? && entries.key?(job_id)
615
+ entries[job_id] = merge_live_entries(entries[job_id], folded)
616
+ elsif !job_id.empty?
617
+ entries[job_id] = folded
618
+ else
619
+ entries[log_file] = folded
620
+ end
621
+ end
622
+ end
623
+
624
+ society_dir = begin
625
+ society_dir_of(base)
626
+ rescue StandardError
627
+ nil
628
+ end
629
+ {
630
+ entries: entries.values,
631
+ scanned: {sidecar: scanned_sidecar,
632
+ agent_view: begin
633
+ File.exist?(base)
634
+ rescue StandardError
635
+ false
636
+ end,
637
+ society: !society_dir.nil? && Dir.exist?(society_dir)}
638
+ }
639
+ end
640
+
641
+ # ------------------------------------------------------------------
642
+ # Agent view: live state of the agent's own save file
643
+ # ------------------------------------------------------------------
644
+ # The `.jobs` sidecar above only sees jobs dispatched through the
645
+ # backend tool round (Workflow.produce inside process_calls). Two live
646
+ # states never appear there:
647
+ #
648
+ # * a "Clean"-type agent (no inference workflow) creates no workflow
649
+ # jobs at all; its only live state is its save file, rewritten at
650
+ # every round boundary by the backend (outgoing-transcript flush)
651
+ # and per completed round by Agent#chat's ensure hook
652
+ # (save_if_configured).
653
+ # * an agent backed by an AgentWorkflow `ask` task writes the
654
+ # immediate `job=` meta at dispatch (Agent#ask) and saves BEFORE
655
+ # producing the job, so the reference dangles in the save file for
656
+ # the whole duration of the running chat task.
657
+ #
658
+ # Save-file location (pinned for callers): a root chat `<base>` keeps
659
+ # its agent conversation at `<base>.files/<agent>.chat`, derived by
660
+ # LLM::Agent.canonical_chat_file(base + '.files', agent_name) where the
661
+ # agent name comes from the chat's `agent:` line (nil means the plain
662
+ # `agent.chat`). This layer takes the save-file PATH as input; the
663
+ # caller resolves it because only it knows the agent name.
664
+
665
+ # Roles that annotate or steer a chat without marking inference state.
666
+ # Trailing ones are skipped when the activity predicate looks for the
667
+ # last conversational message: a file ending in `meta: job=...`
668
+ # (dispatch in flight) still classifies by the prompt that triggered
669
+ # it, and the job reference itself is reported separately by
670
+ # dangling_agent_job_metas.
671
+ AGENT_CONTROL_ROLES = %w[
672
+ meta option sticky_option previous_response_id agent import socialize attachments
673
+ ].freeze
674
+
675
+ # Classify the live activity of one agent save file from its trailing
676
+ # messages. Predicate rules (user-approved heuristic, encoded exactly):
677
+ #
678
+ # last message `user` -> active, :dispatched
679
+ # trailing `function_call` with no
680
+ # `function_call_output` after it -> active, :tool_round_in_flight
681
+ # trailing `function_call_output` -> active, :next_round_pending
682
+ # last message `assistant` with no
683
+ # unresolved function call -> inactive, :idle
684
+ # empty file -> inactive, :no_messages
685
+ # unreadable/missing file -> inactive, :unreadable
686
+ #
687
+ # Control roles (AGENT_CONTROL_ROLES) are skipped when finding the
688
+ # trailing conversational message; any other trailing role (system,
689
+ # introduce, tool) yields inactive :no_inference. Caveat, accepted by
690
+ # design: an `assistant`-terminated file is classified idle during the
691
+ # brief round-boundary window in which a completed round has been
692
+ # saved but the next dispatch has not flushed yet (false negative,
693
+ # never a false positive).
694
+ #
695
+ # ScoutCoder: this predicate is only sound because the backend rewrites
696
+ # the save file with the OUTGOING transcript at every round boundary
697
+ # (the ensure hooks of LLM::Backend::Default#ask) while the agent layer
698
+ # rewrites it with the completed round afterwards (Agent#chat ensure ->
699
+ # save_if_configured). That write cadence is documented nowhere and
700
+ # had to be derived from lib/scout/llm/backends/default.rb.
701
+ def self.agent_log_activity(path)
702
+ path = path.to_s
703
+
704
+ messages = begin
705
+ Chat.load(path)
706
+ rescue StandardError
707
+ return {active: false, reason: :unreadable, last_role: nil,
708
+ message_count: 0, rounds: 0}
709
+ end
710
+
711
+ live_activity_of(messages)
712
+ end
713
+
714
+ # Message-only core of agent_log_activity (see above). Split out so
715
+ # live_chat_state can reuse the classification on a chat it has already
716
+ # loaded; behavior is identical.
717
+ def self.live_activity_of(messages)
718
+ counts = {
719
+ message_count: messages.length,
720
+ rounds: messages.count { |message| message[:role].to_s == 'assistant' }
721
+ }
722
+
723
+ conversational = messages.reject do |message|
724
+ AGENT_CONTROL_ROLES.include?(message[:role].to_s)
725
+ end
726
+ last = conversational.last
727
+
728
+ return {active: false, reason: :no_messages, last_role: nil}.merge(counts) if last.nil?
729
+
730
+ role = last[:role].to_s
731
+ case role
732
+ when 'user'
733
+ {active: true, reason: :dispatched, last_role: role}.merge(counts)
734
+ when 'function_call'
735
+ {active: true, reason: :tool_round_in_flight, last_role: role}.merge(counts)
736
+ when 'function_call_output'
737
+ {active: true, reason: :next_round_pending, last_role: role}.merge(counts)
738
+ when 'assistant'
739
+ {active: false, reason: :idle, last_role: role}.merge(counts)
740
+ else
741
+ {active: false, reason: :no_inference, last_role: role}.merge(counts)
742
+ end
743
+ end
744
+
745
+ # Normalize the forensic "captured" set into plain strings a live
746
+ # reference can be compared against. Entries may be Step objects (the
747
+ # traversal's nodes), Path objects or strings; both the verbatim string
748
+ # and its expanded form are kept, so a short path, a resolved path and
749
+ # a Step all match the same job.
750
+ def self.live_captured_ids(captured)
751
+ entries = captured.respond_to?(:each) ? captured : [captured]
752
+ ids = Set.new
753
+ entries.each do |entry|
754
+ next if entry.nil?
755
+ case entry
756
+ when Step
757
+ path_str = entry.path.to_s
758
+ ids << path_str
759
+ ids << File.expand_path(path_str)
760
+ else
761
+ str = entry.to_s
762
+ ids << str
763
+ ids << File.expand_path(str)
764
+ end
765
+ end
766
+ ids
767
+ end
768
+
769
+ # Collect the `job=` meta references recorded in one agent save file
770
+ # that the forensic report has NOT captured and whose job is still
771
+ # RUNNING (Agent#ask writes the immediate `job=` meta and saves before
772
+ # `job.produce`, so while the chat task runs the reference dangles in
773
+ # the save file, invisible to the `.jobs` sidecar — which never lists
774
+ # the agent's own ask dispatch — and to the forensic traversal, whose
775
+ # result chat does not exist yet).
776
+ #
777
+ # `captured` is the set of job identities the forensic main report
778
+ # already contains (Step, Path or String entries; matched by verbatim
779
+ # reference and by resolved path). Only `:running` jobs survive:
780
+ # finished, crashed, unresolvable and already-captured references are
781
+ # silently dropped, so the method never raises and never reports
782
+ # concluded work. Receipt-borne references (the `meta` arrays inside
783
+ # function_call_output JSON) are deliberately NOT scanned here; they
784
+ # belong to the forensic `:agent_job` relation and describe work whose
785
+ # answer was already consumed.
786
+ def self.dangling_agent_job_metas(path, captured: [])
787
+ path = path.to_s
788
+
789
+ chat = begin
790
+ Chat.load(path)
791
+ rescue StandardError
792
+ return []
793
+ end
794
+
795
+ live_dangling_entries(chat, path, captured: captured)
796
+ end
797
+
798
+ # Reference-only core of dangling_agent_job_metas: the job-references
799
+ # resolution and `:running` reconciliation (everything after Chat.load),
800
+ # split out so live_chat_state can reuse it on a chat it has already
801
+ # loaded; behavior is identical.
802
+ def self.live_dangling_entries(chat, path, captured: [])
803
+ captured_ids = live_captured_ids(captured)
804
+
805
+ references = begin
806
+ chat.jobs
807
+ rescue StandardError
808
+ return []
809
+ end
810
+
811
+ references.collect do |reference|
812
+ ref_str = reference.to_s
813
+ next nil if ref_str.empty?
814
+ next nil if captured_ids.include?(ref_str)
815
+
816
+ step = begin
817
+ load_live_job_reference(ref_str)
818
+ rescue StandardError
819
+ next nil
820
+ end
821
+
822
+ step_id = begin
823
+ File.expand_path(step.path.to_s)
824
+ rescue StandardError
825
+ step.path.to_s
826
+ end
827
+ next nil if captured_ids.include?(step_id)
828
+
829
+ state, status = begin
830
+ classify_live_job(step)
831
+ rescue StandardError
832
+ next nil
833
+ end
834
+ next nil unless state == :running
835
+
836
+ {
837
+ kind: :dangling_job,
838
+ agent_file: path,
839
+ reference: ref_str,
840
+ step: step,
841
+ path: step.path.to_s,
842
+ status: status,
843
+ state: state
844
+ }
845
+ end.compact
846
+ end
847
+
848
+ # Live view of ONE agent save file: its trailing-message activity (the
849
+ # Clean-type gap) plus its dangling `job=` metas reconciled to running
850
+ # jobs (the Direct-type gap). Returns a data-only Array, empty when
851
+ # nothing is live. Entry kinds:
852
+ #
853
+ # :agent_activity -> {kind:, agent_file:, active: true, reason:,
854
+ # last_role:, message_count:, rounds:}
855
+ # :dangling_job -> {kind:, agent_file:, reference:, step:, path:,
856
+ # status:, state:}
857
+ #
858
+ # An inactive agent contributes no activity entry, and a dangling
859
+ # running job is reported on its own, so an agent mid-dispatch (file
860
+ # ending in `meta: job=...`) yields the :dangling_job entry plus the
861
+ # activity entry derived from its trailing conversational message.
862
+ # Fail-soft everywhere: missing or malformed input yields [].
863
+ def self.agent_view_live(save_file, captured: [])
864
+ entries = []
865
+
866
+ state = live_chat_state(save_file, captured: captured)
867
+ activity = state[:activity]
868
+ entries << {kind: :agent_activity, agent_file: save_file.to_s}.merge(activity) if activity[:active]
869
+
870
+ entries.concat(state[:dangling])
871
+ entries
872
+ end
873
+
874
+ # ------------------------------------------------------------------
875
+ # Societal view: live state under <base>.society/
876
+ # ------------------------------------------------------------------
877
+ # ask/hand_off delegation runs in NESTED specialist conversations
878
+ # whose only on-disk trace while running is the society tree written by
879
+ # Agent#save_society
880
+ # (<society_dir>/<agent>/<conversation>/agent.chat, save.rb:239). The
881
+ # forensic traversal deliberately excludes society files
882
+ # (direct_chat_sidecar_files), so a running delegation is invisible to
883
+ # the main report until it completes and its receipt lands in the parent
884
+ # chat. Societal agents have NO main chat to diff against: they are
885
+ # reported whole (activity level), with the stronger dangling `job=`
886
+ # detail added when the child is workflow-backed.
887
+
888
+ # Conservative directory-depth cap for the society scan. One nesting
889
+ # level of society costs three directories (agent/conversation/society),
890
+ # so 128 comfortably covers the agent layer's own SAVE_DEPTH_LIMIT of 32
891
+ # while still bounding a pathological tree.
892
+ SOCIETY_SCAN_DEPTH_LIMIT = 128
893
+
894
+ # Society directory of the agent whose save file is `save_file`.
895
+ #
896
+ # Layout (mirrors LLM::Agent#society_dir, save.rb: the ROOT rule
897
+ # <name>.chat -> <name>.society sibling, and the NESTED rule where a
898
+ # chat already inside a society tree owns a plain `society` sibling, so
899
+ # the tree nests instead of minting new `.files` trees):
900
+ #
901
+ # <base>.files/<name>.chat -> <base>.files/<name>.society
902
+ # <base>.chat -> <base>.society
903
+ # .../<agent>/<conversation>/agent.chat (nested) -> .../<agent>/<conversation>/society
904
+ #
905
+ # The derivation delegates to the agent class (LLM::Agent.society_dir_for
906
+ # / LLM::Agent.nested_save?) so the two cannot drift; the literal mirror
907
+ # below is the fallback when the agent layer is not loaded yet, because
908
+ # chat/provenance is required before scout/llm/agent. Returns nil only
909
+ # when nothing can be derived (empty/nil input); a directory that does
910
+ # not exist on disk is still returned, because existence is the scan's
911
+ # concern, not the derivation's.
912
+ def self.society_dir_of(save_file)
913
+ path = save_file.to_s
914
+ return nil if path.empty?
915
+
916
+ if defined?(LLM::Agent)
917
+ return File.join(File.dirname(path), LLM::Agent::SOCIETY_DIR) if LLM::Agent.nested_save?(path)
918
+ return LLM::Agent.society_dir_for(path)
919
+ end
920
+
921
+ # Mirror of save.rb (keep in sync): nested chat -> sibling 'society';
922
+ # root chat -> <name>.society sibling.
923
+ parent = File.basename(File.dirname(File.dirname(File.dirname(path))))
924
+ if parent == 'society' || parent.end_with?('.society')
925
+ File.join(File.dirname(path), 'society')
926
+ else
927
+ p = path
928
+ p = File.dirname(p) unless p =~ /\.chat\z/
929
+ File.join(File.dirname(p), File.basename(p).sub(/\.chat\z/, '.society'))
930
+ end
931
+ end
932
+
933
+ # Every saved specialist conversation under the society of `save_file`,
934
+ # as a sorted Array of absolute agent.chat paths. Silent [] when the
935
+ # society directory is missing or unreadable.
936
+ #
937
+ # The scan is bounded and closed: it never follows symlinks (a link out
938
+ # of the tree would report work that is not this agent's) and stops at
939
+ # SOCIETY_SCAN_DEPTH_LIMIT directory levels. Only files named
940
+ # `agent.chat` (Agent::SOCIETY_CHAT_FILE, the sole name save_society
941
+ # ever writes) are collected, so a renamed or foreign file is visible as
942
+ # an omission rather than silently reinterpreted.
943
+ def self.society_agent_chats(save_file)
944
+ dir = society_dir_of(save_file)
945
+ return [] if dir.nil? || !File.directory?(dir)
946
+
947
+ chats = []
948
+ scan = lambda do |directory, depth|
949
+ return if depth > SOCIETY_SCAN_DEPTH_LIMIT
950
+
951
+ entries = Dir.entries(directory)
952
+ entries.each do |entry|
953
+ next if entry == '.' || entry == '..'
954
+
955
+ full = File.join(directory, entry)
956
+ next if File.symlink?(full)
957
+
958
+ if File.directory?(full)
959
+ scan.call(full, depth + 1)
960
+ elsif entry == 'agent.chat' && File.file?(full)
961
+ chats << full
962
+ end
963
+ end
964
+ rescue StandardError
965
+ nil
966
+ end
967
+
968
+ scan.call(dir, 0)
969
+ chats.sort
970
+ end
971
+
972
+ # Live view of every specialist conversation under the society of
973
+ # `save_file`. Data-only Array, empty when nothing is live.
974
+ #
975
+ # Per child (path shape <society>/<agent>/<conversation>/agent.chat, with
976
+ # deeper societies nesting under <agent>/<conversation>/society):
977
+ #
978
+ # {kind:, agent:, conversation:, path:, relative:, activity:,
979
+ # job:, job_path:, state:, dangling:}
980
+ #
981
+ # - kind is :dangling_job when the child is WORKFLOW-BACKED and holds a
982
+ # `job=` meta that resolves to a still-running job (the immediate
983
+ # dispatch meta written by Agent#ask before job.produce; the stronger
984
+ # signal, so it wins over activity when both hold), and
985
+ # :agent_activity otherwise.
986
+ # - activity is always included (agent_log_activity of the child file):
987
+ # it is the ONLY signal for PLAIN (non-workflow) children, which
988
+ # dispatch through LLM.ask and never write a `job=` meta at all.
989
+ # - A child is reported when it has a running dangling job OR an active
990
+ # activity classification; finished/idle children are silent.
991
+ # - Dedup: job ids already in `captured` (the forensic main report's set,
992
+ # same matching as dangling_agent_job_metas) never produce a
993
+ # :dangling_job entry; a child whose only live job is captured and
994
+ # whose conversation has concluded is skipped entirely.
995
+ # - Fail-soft: missing society dir, unreadable chats, malformed content
996
+ # and unresolvable job references all degrade to silence, never a
997
+ # raise.
998
+ def self.society_live(save_file, captured: [])
999
+ dir = society_dir_of(save_file)
1000
+ return [] if dir.nil?
1001
+
1002
+ prefix = Regexp.quote(dir) + '/'
1003
+ captured_ids = live_captured_ids(captured)
1004
+
1005
+ society_agent_chats(save_file).collect do |child|
1006
+ state = live_chat_state(child, captured: captured)
1007
+ activity = state[:activity]
1008
+ dangling = state[:dangling]
1009
+
1010
+ # Dedup against the main report: a child whose job reference is
1011
+ # already captured IS that job (a workflow-backed child's whole
1012
+ # current turn is its ask job), so an entry here would report the
1013
+ # same work twice. Skip the child entirely; its conversation is
1014
+ # represented by the captured job in the forensic traversal.
1015
+ child_chat = state[:chat]
1016
+ next nil if child_chat && (child_chat.jobs || []).any? { |ref| captured_ids.include?(ref.to_s) }
1017
+
1018
+ next nil if dangling.empty? && !activity[:active]
1019
+
1020
+ relative = child.sub(/\A#{prefix}/, '')
1021
+ parts = relative.split(File::SEPARATOR)
1022
+
1023
+ entry = {
1024
+ kind: dangling.any? ? :dangling_job : :agent_activity,
1025
+ agent: parts.first,
1026
+ conversation: parts[1],
1027
+ path: child,
1028
+ relative: relative,
1029
+ activity: activity
1030
+ }
1031
+
1032
+ unless dangling.empty?
1033
+ first = dangling.first
1034
+ entry[:job] = first[:reference]
1035
+ entry[:job_path] = first[:path]
1036
+ entry[:state] = first[:state]
1037
+ entry[:dangling] = dangling
1038
+ end
1039
+
1040
+ entry
1041
+ end.compact
1042
+ end
1043
+
1044
+ # Single-load live state of one agent save file: one Chat.load derives
1045
+ # BOTH the trailing-message activity (agent_log_activity's contract) and
1046
+ # the outstanding `job=` references (dangling_agent_job_metas' contract)
1047
+ # for the multi-child paths (society_live, live_report's captured-ref
1048
+ # re-check), where one load serves both consumers.
1049
+ #
1050
+ # Returns {activity: <agent_log_activity hash>, dangling: <Array>,
1051
+ # chat: <Chat or nil>} where `chat` is the loaded object itself
1052
+ # (nil when unreadable; a Chat IS its message Array), because the society
1053
+ # captured-dedup pass also needs the raw job-reference list (chat.jobs)
1054
+ # of the SAME load. Performs NO dedup decision of its own: `dangling`
1055
+ # and `chat` are raw inputs for the caller's existing rules.
1056
+ def self.live_chat_state(path, captured: [])
1057
+ path = path.to_s
1058
+
1059
+ chat = begin
1060
+ Chat.load(path)
1061
+ rescue StandardError
1062
+ chat = nil
1063
+ end
1064
+
1065
+ if chat.nil?
1066
+ {activity: {active: false, reason: :unreadable, last_role: nil,
1067
+ message_count: 0, rounds: 0},
1068
+ dangling: [],
1069
+ chat: nil}
1070
+ else
1071
+ {activity: live_activity_of(chat),
1072
+ dangling: live_dangling_entries(chat, path, captured: captured),
1073
+ chat: chat}
1074
+ end
1075
+ end
1076
+
1077
+ def self.timestamp
1078
+ Time.now.utc.iso8601(3)
1079
+ end
1080
+ end