agent-council 0.1.0 → 0.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.
data/lib/agent_council.rb CHANGED
@@ -3,8 +3,10 @@
3
3
  # AgentCouncil — harness-agnostic orchestration: naming, run-directory
4
4
  # layout, per-agent subprocess execution, and the CLI entry point.
5
5
  # Harness-specific behavior lives under AgentCouncil::Harnesses (e.g.
6
- # AgentCouncil::Harnesses::PiHarness); HARNESS below is the single swap
7
- # point.
6
+ # AgentCouncil::Harnesses::PiHarness), looked up per agent from its config
7
+ # entry's 'harness' key with Harnesses.module_for. A harness's
8
+ # usage(stdout) returns token counts in the shape documented on
9
+ # PiHarness.usage, or nil when the harness reports none.
8
10
 
9
11
  require 'json'
10
12
  require 'yaml'
@@ -20,27 +22,23 @@ require 'shellwords'
20
22
 
21
23
  require_relative 'agent_council/version'
22
24
  require_relative 'agent_council/platform'
23
- require_relative 'agent_council/harnesses/pi_harness'
25
+ require_relative 'agent_council/harnesses'
24
26
  require_relative 'agent_council/worker_pool'
25
27
 
26
28
  module AgentCouncil
27
29
  # Runtime data files (prompt templates) ship inside lib/, resolved
28
30
  # relative to this file, so the gem is self-contained: what gets loaded at runtime never depends on which
29
31
  # files happen to survive the gemspec's file list. PROJECT_ROOT remains
30
- # only for documentation references (e.g. the local README path in help
31
- # text), not for runtime data.
32
+ # only for locating documentation and examples (the local paths in help
33
+ # text, and what --gem-dir prints), not for runtime data.
32
34
  PROJECT_ROOT = File.expand_path('..', __dir__)
35
+ # Matches the gemspec's homepage (a spec checks).
36
+ PROJECT_URL = 'https://github.com/keithrbennett/agent-council'
33
37
  EXAMPLES_DIR = File.join(PROJECT_ROOT, 'examples')
34
38
  TEMPLATES_DIR = File.join(__dir__, 'agent_council', 'templates')
35
39
  CONSOLIDATE_PROMPT_PATH = File.join(TEMPLATES_DIR, 'consolidate_prompt.md')
36
40
  ANALYST_FORMAT_PATH = File.join(TEMPLATES_DIR, 'analyst_format.md')
37
41
 
38
- # The harness every model runs through; the single swap point. A second
39
- # harness would be another module under AgentCouncil::Harnesses,
40
- # assigned here. Its usage(stdout) returns token counts in the shape
41
- # documented on PiHarness.usage, or nil when the harness reports none.
42
- HARNESS = AgentCouncil::Harnesses::PiHarness
43
-
44
42
  # After Ctrl-C, how long agents get to exit after SIGTERM before they're
45
43
  # killed (see WorkerPool).
46
44
  INTERRUPT_GRACE_SECONDS = 5
@@ -120,28 +118,43 @@ module AgentCouncil
120
118
  # self-describing when copied out of the reports tree. index (an agent's
121
119
  # 1-based position in the config's agent list) disambiguates repeated
122
120
  # provider/model entries — e.g. the same model configured twice for two
123
- # independent analyses — without depending on it being unique. It sits before the harness so that once more than one harness
124
- # exists, filenames still sort in config/agent order first, rather than
125
- # grouping by harness.
126
- module_function def report_filename(file_prefix, provider, model, index: nil)
121
+ # independent analyses — without depending on it being unique. It sits
122
+ # before the harness so that, with more than one harness, filenames sort
123
+ # in config/agent order first, rather than grouping by harness.
124
+ # agent: its config entry.
125
+ module_function def report_filename(file_prefix, agent, index: nil)
127
126
  parts = [file_prefix]
128
127
  parts << format('%02d', index) if index
129
- parts << HARNESS::NAME
130
- parts += [sanitize(provider), sanitize(model)]
128
+ parts << Harnesses.name_of(agent)
129
+ parts += [sanitize(agent['provider']), sanitize(agent['model'])]
131
130
  "#{parts.join('_')}.md"
132
131
  end
133
132
 
134
- # Returns [label, ok, detail, usage]; never raises. usage is the run's
135
- # token usage (see HARNESS), or nil; failed runs report it too, since
136
- # their tokens were still spent.
133
+ # The variables set for an agent's process: the scratch dir as its
134
+ # TMPDIR, which the scaffolding tells agents to use, and as
135
+ # CLAUDE_CODE_TMPDIR, the base under which Claude Code's sandbox makes
136
+ # the writable TMPDIR it gives commands. Without the latter, a user's
137
+ # own CLAUDE_CODE_TMPDIR would put that dir outside the scratch dir,
138
+ # shared and never cleaned up. pi ignores it.
139
+ module_function def agent_env(scratch_dir)
140
+ { 'TMPDIR' => scratch_dir, 'CLAUDE_CODE_TMPDIR' => scratch_dir }
141
+ end
142
+
143
+ # Returns [label, ok, detail, usage, warnings]; never raises. detail is
144
+ # the report's filename on success, the error otherwise. usage is the
145
+ # agent's token usage (see Harnesses), or nil; failed agents report it too,
146
+ # since their tokens were still spent. warnings: the harness's warnings
147
+ # about the agent (see run_warnings), failed or not, since what the harness
148
+ # kept the agent from doing may be why it failed; empty if the harness
149
+ # never ran. Returned, not printed, since this runs in a worker thread.
137
150
  # index: the agent's 1-based position in the config's agent list, used to
138
151
  # disambiguate repeated provider/model entries in the filename and label;
139
152
  # filename: overrides the output name; meta: becomes YAML front matter,
140
- # which identifies the report; what was measured about its run (duration
153
+ # which identifies the report; what was measured about the agent (duration
141
154
  # and usage) goes in run.json instead (see write_run_file);
142
155
  # header: markdown prepended to the report body (or a callable receiving
143
- # the run's fields, 'duration' (HH:MM:SS) and 'usage', and returning
144
- # it). If the response begins
156
+ # the agent's fields, 'duration' (HH:MM:SS), 'usage', and any 'warnings',
157
+ # and returning it). If the response begins
145
158
  # with an H1 of its own, it is dropped: the header leads the body (and
146
159
  # carries the title, in consolidated reports).
147
160
  # pool: the WorkerPool to spawn the agent through, so Ctrl-C can stop it;
@@ -151,65 +164,126 @@ module AgentCouncil
151
164
  provider = agent['provider'] if agent.is_a?(Hash)
152
165
  model = agent['model'] if agent.is_a?(Hash)
153
166
  label = agent_label(provider, model, index)
154
- return [label, false, "config entry needs 'provider' and 'model'"] if provider.nil? || model.nil?
167
+ # Config entries are validated at startup; this guards direct callers.
168
+ if (error = entry_error(agent))
169
+ return [label, false, "config entry #{error}", nil, []]
170
+ end
155
171
 
156
172
  # Removed in the ensure below rather than via Dir.mktmpdir's block form,
157
173
  # with errors ignored: a child that is still exiting (e.g. one just
158
174
  # killed after the Ctrl-C grace period) can still be writing here
159
175
  # (node's compile cache, say). That must not surface as an error.
176
+ harness = Harnesses.module_for(agent)
160
177
  scratch_dir = Dir.mktmpdir('agent-council-')
161
- argv = HARNESS.argv(provider, model, scratch_dir)
178
+ argv = harness.argv(provider, model)
162
179
  (stdout, stderr, status), elapsed = timed do
163
- (pool || Open3).capture3({ 'TMPDIR' => scratch_dir }, *argv, stdin_data: prompt)
180
+ (pool || Open3).capture3(agent_env(scratch_dir), *argv, stdin_data: prompt)
164
181
  end
165
182
  # Harness output is UTF-8. WorkerPool#capture3 already returns it as such,
166
183
  # but Open3.capture3 (used without a pool) returns the locale's encoding.
167
184
  stdout, stderr = [stdout, stderr].map { |output| String.new(output, encoding: ENCODING) }
185
+ # Invalid bytes become U+FFFD, so they can't make the harness's parsing
186
+ # raise: for stderr, a failure would go unexplained; for stdout, a
187
+ # failure's reason or an agent's warnings would be lost.
188
+ stdout, stderr = [stdout, stderr].map(&:scrub)
168
189
  duration = format_duration(elapsed)
169
- usage = HARNESS.usage(stdout)
190
+ usage = harness.usage(stdout)
191
+ # Read before the report is written, so its byline can show them (and
192
+ # so the consolidator, which reads the report, learns of them).
193
+ warnings = run_warnings(harness, stdout)
170
194
 
171
195
  unless status.success?
172
- detail = stderr.lines.map(&:strip).reject(&:empty?).first || 'no error output'
173
- return [label, false, "#{HARNESS::NAME} exited #{status.exitstatus}: #{detail}", usage]
196
+ detail = failure_reason(harness.exit_detail(stdout, stderr))
197
+ return [label, false, "#{harness::NAME} exited #{status.exitstatus}: #{detail}", usage, warnings]
174
198
  end
175
199
 
176
- error = HARNESS.error_message(stdout)
200
+ error = harness.error_message(stdout)
177
201
  if error
178
- summary = error.gsub(/\s+/, ' ').slice(0, 300)
179
- return [label, false, "#{HARNESS::NAME} exited 0 but the run failed: #{summary}", usage]
202
+ summary = failure_reason(error)
203
+ return [label, false, "#{harness::NAME} exited 0 but the agent failed: #{summary}", usage, warnings]
180
204
  end
181
205
 
182
- text = HARNESS.final_response(stdout)
206
+ text = harness.final_response(stdout)
183
207
  if text.nil? || text.strip.empty?
184
208
  detail =
185
- if HARNESS.assistant_messages(stdout).any?
209
+ if harness.assistant_messages(stdout).any?
186
210
  'final assistant message had no text content (model may have answered in reasoning only)'
187
211
  else
188
- "no assistant message in #{HARNESS::NAME} event stream"
212
+ "no assistant message in #{harness::NAME} event stream"
189
213
  end
190
- return [label, false, "#{HARNESS::NAME} exited 0 but #{detail}", usage]
214
+ return [label, false, "#{harness::NAME} exited 0 but #{detail}", usage, warnings]
191
215
  end
192
216
 
193
- filename ||= report_filename(file_prefix, provider, model, index: index)
194
- run_fields = { 'duration' => duration, 'usage' => usage }.compact
217
+ filename ||= report_filename(file_prefix, agent, index: index)
218
+ run_fields = { 'duration' => duration, 'usage' => usage, 'warnings' => warnings.empty? ? nil : warnings }
219
+ .compact
195
220
  if header
196
221
  header = header.call(run_fields) if header.respond_to?(:call)
197
222
  text = text.sub(/\A\s*#(?!#).+\n+/, '')
198
223
  text = "#{header}\n#{text}"
199
224
  end
200
- content = with_front_matter(meta.merge('harness' => HARNESS::NAME,
225
+ content = with_front_matter(meta.merge('harness' => Harnesses.name_of(agent),
201
226
  'provider' => provider,
202
227
  'model' => model), text)
203
228
  # Exclusive create ('x'): never replaces a report, e.g. one written by
204
229
  # a concurrent --consolidate with the same model; that is a failure.
205
230
  File.write(File.join(run_dir, filename), content, mode: 'wx')
206
- [label, true, filename, usage]
231
+ [label, true, filename, usage, warnings]
207
232
  rescue => e
208
- [label, false, "#{e.class}: #{e.message}", usage]
233
+ [label, false, failure_reason("#{e.class}: #{e.message}"), usage, Array(warnings)]
209
234
  ensure
210
235
  FileUtils.rm_rf(scratch_dir) if scratch_dir
211
236
  end
212
237
 
238
+ # The harness's warnings about an agent: what the harness kept it
239
+ # from doing (see ClaudeCodeHarness.warnings), which a report may lack,
240
+ # or which may be why the agent failed. Advisory only: failing to read them
241
+ # must not fail an agent whose report is saved, so that becomes a warning
242
+ # too.
243
+ # Each is a plain_line, so wherever it goes (console, report, run.json,
244
+ # and so anything that prints run.json's values) it can't carry a
245
+ # terminal escape from a command the model wrote.
246
+ module_function def run_warnings(harness, stdout)
247
+ # An Array, by the harness contract; nil tolerated.
248
+ Array(harness.warnings(stdout)).map { |warning| plain_line(warning) }
249
+ rescue => e
250
+ [plain_line("could not read the agent's warnings (#{e.class}: #{e.message})")]
251
+ end
252
+
253
+ # A harness's reason for a failure, as run_agent reports it: a
254
+ # plain_line, since it can quote the model or the CLI, cut to 300
255
+ # characters plus "..." so it doesn't swamp the progress line, the Errors
256
+ # list, or the consolidation prompt; 'no error output' if nothing is left.
257
+ module_function def failure_reason(text)
258
+ reason = plain_line(text)
259
+ return 'no error output' if reason.empty?
260
+
261
+ reason.length > 300 ? "#{reason[0, 300]}..." : reason
262
+ end
263
+
264
+ # Lines showing an agent's warnings under its progress line or result table.
265
+ module_function def warning_lines(warnings)
266
+ Array(warnings).map { |warning| " Warning: #{plain_line(warning)}" }
267
+ end
268
+
269
+ # Text on one line with no control characters: every run of whitespace
270
+ # or control characters (newlines, carriage returns, the ESC that starts
271
+ # a terminal escape sequence) becomes one space; the rest of an escape
272
+ # sequence, such as "[2J", stays as harmless text. Warnings can quote a
273
+ # model's refused command, so this keeps one from moving the cursor or
274
+ # clearing the screen when printed, or from breaking the line it appears
275
+ # on in a report. Text in any encoding is read as UTF-8 (a SystemCallError's
276
+ # message can be binary). Invisible format characters (Unicode category Cf, such
277
+ # as bidirectional overrides and zero-width spaces) are removed, so text
278
+ # can't display reordered or hide characters. Invalid bytes become U+FFFD,
279
+ # since this also runs in rescue clauses and must not raise.
280
+ module_function def plain_line(text)
281
+ # Alternation, not one bracket class: the two overlap, which ruby -w
282
+ # warns of.
283
+ String.new(text.to_s, encoding: ENCODING).scrub.gsub(/\p{Cf}/, '')
284
+ .gsub(/(?:[[:space:]]|[[:cntrl:]])+/, ' ').strip
285
+ end
286
+
213
287
  # Creates a new run dir in day_dir and returns its name: base, or base-2,
214
288
  # base-3, ... if that is taken. Dir.mkdir fails if the dir exists, so the
215
289
  # claim is atomic: runs started in the same second (or whose local time
@@ -294,15 +368,17 @@ module AgentCouncil
294
368
 
295
369
  # The consolidator's substantive prompt: the instructions template, the
296
370
  # original prompt every analyst answered, all reports with their source
297
- # labels, and the agents without a report, as [label, reason] pairs; the
298
- # consolidator can't otherwise know about those.
371
+ # labels, and the agents without a report, as [label, reason, harness]
372
+ # triples; the consolidator can't otherwise know about those.
299
373
  module_function def consolidation_prompt(original_prompt, reports, failures = [])
300
374
  template = File.read(CONSOLIDATE_PROMPT_PATH, encoding: ENCODING)
301
375
  body = reports.map do |label, text, fields|
302
- harness = (fields && fields['harness']) || HARNESS::NAME
303
- "## Report from #{label}\n\nHarness: #{harness}\n\n#{text}"
376
+ "## Report from #{label}\n\nHarness: #{Harnesses.name_of(fields)}\n\n#{text}"
304
377
  end.join("\n\n---\n\n")
305
- failed = failures.empty? ? 'None.' : failures.map { |label, reason| "- #{label}: #{reason}" }.join("\n")
378
+ failed = failures.map do |label, reason, harness|
379
+ "- #{label}#{" (harness: #{plain_line(harness)})" if harness}: #{plain_line(reason)}"
380
+ end
381
+ failed = failures.empty? ? 'None.' : failed.join("\n")
306
382
  <<~MARKDOWN
307
383
  #{template}
308
384
 
@@ -330,9 +406,11 @@ module AgentCouncil
330
406
  # dir, and stays self-describing when copied out of the tree.
331
407
  # part: 'findings' or 'meta' for the files a consolidated report is split
332
408
  # into (see split_consolidated_report); none for the report as written.
333
- module_function def consolidated_filename(file_prefix, provider, model, part = nil)
409
+ # consolidator: its config entry.
410
+ module_function def consolidated_filename(file_prefix, consolidator, part = nil)
334
411
  suffix = part ? "_#{part}" : ''
335
- "#{file_prefix}_consolidated_#{HARNESS::NAME}_#{sanitize(provider)}_#{sanitize(model)}#{suffix}.md"
412
+ names = consolidator.values_at('provider', 'model').map { |name| sanitize(name) }
413
+ "#{file_prefix}_consolidated_#{[Harnesses.name_of(consolidator), *names].join('_')}#{suffix}.md"
336
414
  end
337
415
 
338
416
  # The line the consolidator is asked to write between its findings and
@@ -343,7 +421,7 @@ module AgentCouncil
343
421
  # <model>", for the findings file's legend.
344
422
  module_function def full_label(fields)
345
423
  index = fields['agent_index']
346
- parts = [fields['harness'] || HARNESS::NAME, fields['provider'], fields['model']].join(' / ')
424
+ parts = [Harnesses.name_of(fields), fields['provider'], fields['model']].join(' / ')
347
425
  index ? "##{index} #{parts}" : parts
348
426
  end
349
427
 
@@ -395,13 +473,14 @@ module AgentCouncil
395
473
  # identifying the run, for its top. Returns the findings filename and the
396
474
  # meta filename, or, if the report can't be split or the split files
397
475
  # can't be written, the report under the unsplit name (see
398
- # consolidated_filename) and nil, with a warning.
399
- module_function def split_consolidated_report(run_dir, filename, file_prefix, provider, model, head,
400
- labels, info = [])
401
- path = File.join(run_dir, filename)
402
- unsplit_name = consolidated_filename(file_prefix, provider, model)
403
- findings_name = consolidated_filename(file_prefix, provider, model, 'findings')
476
+ # consolidated_filename) and nil, with a warning. consolidator: its
477
+ # config entry, which names the split files.
478
+ module_function def split_consolidated_report(run_dir, filename, file_prefix, consolidator, head, labels,
479
+ info = [])
404
480
  written = []
481
+ path = File.join(run_dir, filename)
482
+ unsplit_name = consolidated_filename(file_prefix, consolidator)
483
+ findings_name = consolidated_filename(file_prefix, consolidator, 'findings')
405
484
  content = File.read(path, encoding: ENCODING)
406
485
  front = content[/\A---\n.+?\n---\n\n?/m] || ''
407
486
  body = content.delete_prefix(front)
@@ -435,8 +514,12 @@ module AgentCouncil
435
514
  File.rename(temp, path)
436
515
  [findings_name, filename]
437
516
  rescue => e
438
- # A failed split must not fail the consolidation, whose model run is
439
- # already paid for and whose report is intact.
517
+ # A failed split must not fail the consolidation, whose model call is
518
+ # already paid for and whose report is intact. Without an unsplit name
519
+ # (a consolidator entry that can't name a file, which validation rules
520
+ # out), there is nothing to fall back to, so the error is raised as is.
521
+ raise unless unsplit_name
522
+
440
523
  warn "Could not split #{relative_path(path)}: #{e.message}"
441
524
  written.each { |name| FileUtils.rm_f(File.join(run_dir, name)) }
442
525
  keep_unsplit(run_dir, filename, unsplit_name)
@@ -459,23 +542,24 @@ module AgentCouncil
459
542
  [filename, nil]
460
543
  end
461
544
 
462
- # Markdown table of the report's main front-matter fields and its run's
545
+ # Markdown table of the report's main front-matter fields and the agent's
463
546
  # duration and usage, leading the body (under the title, in consolidated
464
- # reports, followed by sources_table).
465
- module_function def byline_table(meta, provider, model)
547
+ # reports, followed by sources_table). agent: the agent's config entry.
548
+ module_function def byline_table(meta, agent)
466
549
  fields = {
467
550
  'role' => meta['role'],
468
551
  'agent' => (meta['agent_index'] ? "##{meta['agent_index']}" : nil),
469
552
  'query' => meta['query'],
470
- 'harness' => HARNESS::NAME,
471
- 'provider' => provider,
472
- 'model' => model,
553
+ 'harness' => Harnesses.name_of(agent),
554
+ 'provider' => agent['provider'],
555
+ 'model' => agent['model'],
473
556
  'timestamp' => meta['timestamp'],
474
557
  'consolidated_at' => meta['consolidated_at'],
475
558
  'duration' => meta['duration'],
476
559
  'usage' => format_usage(meta['usage']),
560
+ 'warnings' => (Array(meta['warnings']).join('; ') unless Array(meta['warnings']).empty?),
477
561
  }.compact
478
- rows = fields.map { |field, value| "| #{field} | #{value} |" }
562
+ rows = fields.map { |field, value| "| #{field} | #{table_cell(value)} |" }
479
563
  <<~TABLE
480
564
  | Field | Value |
481
565
  | :-------- | :---------------------------- |
@@ -483,8 +567,15 @@ module AgentCouncil
483
567
  TABLE
484
568
  end
485
569
 
570
+ # A value as one Markdown table cell: a plain_line, with its pipes and
571
+ # backslashes escaped, so text such as a refused `a | b` or `grep '\|'`
572
+ # command can't add columns or rows.
573
+ module_function def table_cell(value)
574
+ plain_line(value).gsub(/[\\|]/) { |char| "\\#{char}" }
575
+ end
576
+
486
577
  # Markdown table of a consolidated report's sources, one row per label in
487
- # sources, with its run's duration and usage from source_runs (label =>
578
+ # sources, with that agent's duration and usage from source_runs (label =>
488
579
  # run.json entry); - where unknown. Input counts cached input too.
489
580
  module_function def sources_table(sources, source_runs)
490
581
  rows = sources.map do |label|
@@ -503,10 +594,11 @@ module AgentCouncil
503
594
  end
504
595
 
505
596
  # Runs the configured consolidator model over a run's reports and writes
506
- # its report into the same run dir. Returns as run_agent, except that
597
+ # its report into the same run dir. Returns [label, ok, detail, usage,
598
+ # meta_name, warnings], as run_agent does with meta_name inserted:
507
599
  # detail is the findings file's name when the report was split (see
508
- # split_consolidated_report) and the meta file's name follows usage;
509
- # never raises.
600
+ # split_consolidated_report), and meta_name the meta file's (nil when
601
+ # unsplit or failed); never raises.
510
602
  # analyst_runs: the run's run.json analyst entries, for the sources
511
603
  # table's durations and usage. failures: as for consolidation_prompt.
512
604
  # pool: as for run_agent.
@@ -514,12 +606,14 @@ module AgentCouncil
514
606
  meta: {}, prompt_path: nil, failures: [], analyst_runs: [], pool: nil)
515
607
  provider = consolidator['provider'] if consolidator.is_a?(Hash)
516
608
  model = consolidator['model'] if consolidator.is_a?(Hash)
517
- return ['consolidator', false, "config entry needs 'provider' and 'model'"] if provider.nil? || model.nil?
609
+ if (error = entry_error(consolidator))
610
+ return ['consolidator', false, "config entry #{error}", nil, nil, []]
611
+ end
518
612
 
519
613
  reports = collect_reports(File.join(run_dir, REVIEWS_DIR_NAME))
520
614
  if reports.empty?
521
615
  return [agent_label(provider, model), false,
522
- "no reports found in #{relative_path(File.join(run_dir, REVIEWS_DIR_NAME))}"]
616
+ "no reports found in #{relative_path(File.join(run_dir, REVIEWS_DIR_NAME))}", nil, nil, []]
523
617
  end
524
618
 
525
619
  prompt = consolidation_prompt(original_prompt, reports, failures)
@@ -532,25 +626,27 @@ module AgentCouncil
532
626
  prompt_line = prompt_path ? "### Prompt: #{prompt_path}\n\n" : ''
533
627
  head = nil
534
628
  header = ->(run_fields) do
535
- head = "# Consolidated Report\n\n#{prompt_line}#{byline_table(meta.merge(run_fields), provider,
536
- model)}\n" \
629
+ head = "# Consolidated Report\n\n#{prompt_line}" \
630
+ "#{byline_table(meta.merge(run_fields), consolidator)}\n" \
537
631
  "#{sources_table(meta['sources'], source_runs)}"
538
632
  end
539
- label, ok, detail, usage = run_agent(consolidator, prompt, run_dir, file_prefix,
540
- filename: consolidated_filename(file_prefix, provider, model, 'meta'),
633
+ label, ok, detail, usage, warnings = run_agent(consolidator, prompt, run_dir, file_prefix,
634
+ filename: consolidated_filename(file_prefix, consolidator, 'meta'),
541
635
  header: header,
542
636
  meta: meta,
543
637
  pool: pool)
638
+ warnings = Array(warnings)
544
639
  if ok
545
640
  labels = reports.map { |_, _, fields| full_label(fields) }
546
641
  info = ["Run: #{file_prefix}", prompt_path && "Prompt: #{File.basename(prompt_path)}",
547
- "Consolidated by: #{HARNESS::NAME} / #{provider} / #{model}, #{meta['consolidated_at']}"].compact
548
- detail, meta_name = split_consolidated_report(run_dir, detail, file_prefix, provider, model, head,
549
- labels, info)
642
+ "Consolidated by: #{agent_descriptor(consolidator)}, #{meta['consolidated_at']}",
643
+ ("Consolidator warnings: #{plain_line(warnings.join('; '))}" unless warnings.empty?)].compact
644
+ detail, meta_name = split_consolidated_report(run_dir, detail, file_prefix, consolidator, head, labels,
645
+ info)
550
646
  end
551
- [label, ok, detail, usage, meta_name]
647
+ [label, ok, detail, usage, meta_name, warnings]
552
648
  rescue => e
553
- [agent_label(provider, model), false, "#{e.class}: #{e.message}"]
649
+ [agent_label(provider, model), false, failure_reason("#{e.class}: #{e.message}"), nil, nil, []]
554
650
  end
555
651
 
556
652
  module_function def relative_path(path)
@@ -572,7 +668,7 @@ module AgentCouncil
572
668
  format('%02d:%02d:%02d', total / 3600, total % 3600 / 60, total % 60)
573
669
  end
574
670
 
575
- # Token usage (see HARNESS) as e.g. "1.2M in (900.0k cached) / 30.5k out,
671
+ # Token usage (see Harnesses) as e.g. "1.2M in (900.0k cached) / 30.5k out,
576
672
  # $0.85", where "in" counts all input, cached or not. The cost is left out
577
673
  # when unknown. nil for nil usage.
578
674
  module_function def format_usage(usage)
@@ -593,7 +689,7 @@ module AgentCouncil
593
689
  end
594
690
 
595
691
  # [input (cached or not), cached input, output, cost (nil when unknown)]
596
- # from a usage hash (see HARNESS), or nil for unknown usage.
692
+ # from a usage hash (see Harnesses), or nil for unknown usage.
597
693
  module_function def usage_figures(usage)
598
694
  return nil unless usage.is_a?(Hash)
599
695
 
@@ -613,7 +709,7 @@ module AgentCouncil
613
709
  dollars < 0.01 ? '<$0.01' : format('$%.2f', dollars)
614
710
  end
615
711
 
616
- # The sum of usage hashes (see HARNESS), ignoring nils (and anything else
712
+ # The sum of usage hashes (see Harnesses), ignoring nils (and anything else
617
713
  # not a hash); nil if there are none.
618
714
  # The cost is summed only if every usage has one, so a partial total
619
715
  # isn't presented as the whole.
@@ -626,25 +722,28 @@ module AgentCouncil
626
722
  costs.all?(Numeric) ? total.merge('cost' => costs.sum.round(6)) : total
627
723
  end
628
724
 
629
- # The run dir's machine-readable record of its agents' runs.
725
+ # The run dir's machine-readable record of its analysts and consolidations.
630
726
  RUN_FILENAME = 'run.json'
631
727
 
632
728
  # A run.json entry for an agent's run_agent result and its elapsed
633
729
  # seconds: its report's path under dir (the run dir's reviews_dir for
634
730
  # analysts) on success, its error on failure. The harness is per entry,
635
- # not per run, so a run can mix harnesses. meta_report: for a
731
+ # so a run can mix harnesses. meta_report: for a
636
732
  # consolidation whose report was split (its detail is the findings file's
637
- # name), the other file, which carries the front matter.
638
- module_function def run_entry(agent, ok, detail, elapsed, usage, index: nil, dir: nil, meta_report: nil)
639
- entry = { 'agent_index' => index, 'harness' => HARNESS::NAME, 'provider' => agent['provider'],
733
+ # name), the other file, which carries the front matter. warnings: the
734
+ # agent's warnings (see run_agent), recorded only if there are any.
735
+ module_function def run_entry(agent, ok, detail, elapsed, usage, index: nil, dir: nil, meta_report: nil,
736
+ warnings: nil)
737
+ entry = { 'agent_index' => index, 'harness' => Harnesses.name_of(agent), 'provider' => agent['provider'],
640
738
  'model' => agent['model'], 'ok' => ok }.compact
641
739
  entry[ok ? 'report' : 'error'] = ok && dir ? File.join(dir, detail) : detail
642
740
  entry['meta_report'] = (dir ? File.join(dir, meta_report) : meta_report) if ok && meta_report
741
+ entry['warnings'] = warnings if warnings.is_a?(Array) && !warnings.empty?
643
742
  entry.merge('duration_seconds' => elapsed.round(1), 'usage' => usage)
644
743
  end
645
744
 
646
745
  # Writes the run dir's run.json: every analyst's and consolidation's
647
- # entry (see run_entry), their total usage, and how many runs it covers
746
+ # entry (see run_entry), their total usage, and how many entries it covers
648
747
  # (those that reported usage). Replaced atomically, so a
649
748
  # reader or a Ctrl-C never sees it half written. A failure to write it is
650
749
  # only warned about: the reports are what matter.
@@ -683,9 +782,10 @@ module AgentCouncil
683
782
  RIGHT_ALIGNED_COLUMNS = (3..6)
684
783
 
685
784
  # Indented result table lines for [label, ok, detail, elapsed, usage]
686
- # results: a heading row, then one row per result, with ✓ or ✗ and its
687
- # usage (as for usage_cells), then the failures' errors, if any, listed
688
- # below the table so long messages don't widen it. Report filenames
785
+ # results (any further elements, such as warnings, are ignored): a
786
+ # heading row, then one row per result, with ✓ or ✗ and its usage (as
787
+ # for usage_cells), then the failures' errors, if any, listed below the
788
+ # table so long messages don't widen it. Report filenames
689
789
  # aren't shown: an analyst's is found by its agent number, and the
690
790
  # consolidated report is at the run dir's top level.
691
791
  module_function def format_result_table(results)
@@ -705,7 +805,7 @@ module AgentCouncil
705
805
  errors.empty? ? lines : [*lines, '', ' Errors:', *errors]
706
806
  end
707
807
 
708
- # "; <total usage>" for a summary line, noting how many of the runs it
808
+ # "; <total usage>" for a summary line, noting how many of the agents it
709
809
  # covers when some reported no usage; "" when none reported any.
710
810
  module_function def usage_summary(usages)
711
811
  total = format_usage(sum_usage(usages))
@@ -738,12 +838,105 @@ module AgentCouncil
738
838
  puts "\n--- Consolidation #{ok ? 'complete' : 'error'} ---"
739
839
  end
740
840
 
741
- # True if a config entry (agent or consolidator) has the required string
742
- # 'provider' and 'model' fields.
743
- module_function def valid_agent_entry?(entry)
841
+ # True if a config entry (agent or consolidator) has the string 'provider'
842
+ # and 'model' fields its label is made from.
843
+ module_function def labelable_entry?(entry)
744
844
  entry.is_a?(Hash) && entry['provider'].is_a?(String) && entry['model'].is_a?(String)
745
845
  end
746
846
 
847
+ # The keys every config entry (agent or consolidator) must give, each a
848
+ # nonblank string. None has a default: a default harness or provider
849
+ # would go stale as harnesses change, so a config says what it runs.
850
+ ENTRY_KEYS = %w[harness provider model].freeze
851
+
852
+ # What kind of YAML value a value is, for error messages.
853
+ module_function def yaml_kind(value)
854
+ case value
855
+ when Hash then 'a mapping'
856
+ when Array then 'a list'
857
+ when String then 'a string'
858
+ when nil then 'null'
859
+ when true, false then 'a boolean'
860
+ when Numeric then 'a number'
861
+ else "a #{value.class.name.downcase}" # unreachable from safe_load, which rejects dates
862
+ end
863
+ end
864
+
865
+ # 'a', 'a' and 'b', 'a', 'b', and 'c': names quoted and joined.
866
+ module_function def quoted_list(names)
867
+ quoted = names.map { |name| "'#{name}'" }
868
+ quoted.size < 3 ? quoted.join(' and ') : "#{quoted[0..-2].join(', ')}, and #{quoted.last}"
869
+ end
870
+
871
+ # Why a config entry can't be run, as a phrase following the entry's
872
+ # name, or nil if it can: it must be a mapping giving each of ENTRY_KEYS
873
+ # as a nonblank string, and its harness must be a known one. Every
874
+ # problem is named, so one edit can fix them all.
875
+ module_function def entry_error(entry)
876
+ known = Harnesses::BY_NAME.keys
877
+ return "must be a mapping giving #{entry_needs}, but is #{yaml_kind(entry)}" unless entry.is_a?(Hash)
878
+
879
+ missing = ENTRY_KEYS.select { |key| entry[key].nil? }
880
+ blank = ENTRY_KEYS.select { |key| entry[key].is_a?(String) && blank_value?(entry[key]) }
881
+ non_strings = ENTRY_KEYS.reject { |key| entry[key].nil? || entry[key].is_a?(String) }
882
+ problems = []
883
+ problems << "is missing #{quoted_list(missing)}" unless missing.empty?
884
+ unless blank.empty?
885
+ problems << "gives #{blank.size == 1 ? 'a blank' : 'blank values for'} #{quoted_list(blank)}"
886
+ end
887
+ non_strings.each do |key|
888
+ value = entry[key]
889
+ # Quoting fixes a scalar YAML read as a number, date, or boolean, but
890
+ # no quoted value but a known name makes a harness valid.
891
+ fix =
892
+ if key == 'harness' then " (known: #{known.join(', ')})"
893
+ elsif !value.is_a?(Hash) && !value.is_a?(Array) then ' (quote it)'
894
+ end
895
+ problems << "gives '#{key}' as #{yaml_kind(value)}, #{value.inspect}, not a string#{fix}"
896
+ end
897
+ harness = entry['harness']
898
+ if harness.is_a?(String) && !blank_value?(harness) && !known.include?(harness)
899
+ problems << "names an unknown harness, #{harness.inspect} (known: #{known.join(', ')})"
900
+ end
901
+ return if problems.empty?
902
+
903
+ problems.join('; ')
904
+ end
905
+
906
+ # The keys every entry gives, with the known harnesses.
907
+ module_function def entry_needs
908
+ "#{quoted_list(ENTRY_KEYS)} (harness: #{Harnesses::BY_NAME.keys.join(', ')})"
909
+ end
910
+
911
+ # True if a config value counts as missing: absent, null, or blank.
912
+ module_function def blank_value?(value)
913
+ value.nil? || (value.is_a?(String) && value.strip.empty?)
914
+ end
915
+
916
+ # Added after the errors when an entry gives no harness, which may be
917
+ # one from a 0.1.0 config, when every entry ran under pi.
918
+ MISSING_HARNESS_HINT =
919
+ "If this is a 0.1.0 config, it ran every entry under pi: add 'harness: pi' to each entry."
920
+
921
+ # Aborts, if any of entries (a Hash of name, e.g. "'agents' entry #2", to
922
+ # config entry) has an error, with one line per bad entry, naming the
923
+ # config file, so one edit can fix them all. When a bad entry is a
924
+ # mapping without a harness, a line saying what every entry needs
925
+ # follows, and then hint, if no entry gives a harness (as in a 0.1.0
926
+ # config; a config that names some may have a typo instead).
927
+ module_function def abort_on_entry_errors(entries, config_path, hint: MISSING_HARNESS_HINT)
928
+ bad = entries.filter_map { |name, entry| (error = entry_error(entry)) && [name, entry, error] }
929
+ return if bad.empty?
930
+
931
+ lines = bad.map { |name, _entry, error| "#{name} in #{config_path} #{error}" }
932
+ harnessless = ->(entry) { entry.is_a?(Hash) && blank_value?(entry['harness']) }
933
+ if bad.any? { |_name, entry, _error| harnessless.(entry) }
934
+ lines << "Every entry needs #{entry_needs}."
935
+ lines << hint if entries.values.all?(&harnessless)
936
+ end
937
+ abort lines.join("\n")
938
+ end
939
+
747
940
  # True if `name` (a bare command name) is an executable file in a PATH
748
941
  # directory. Checked up front so a missing harness fails before any run
749
942
  # dir is created, rather than as an Errno::ENOENT from every agent. An
@@ -759,7 +952,7 @@ module AgentCouncil
759
952
  # "harness / provider / model" for a validated config entry, printed at
760
953
  # startup so it is clear which agents are still running later.
761
954
  module_function def agent_descriptor(entry)
762
- "#{HARNESS::NAME} / #{entry['provider']} / #{entry['model']}"
955
+ "#{Harnesses.name_of(entry)} / #{entry['provider']} / #{entry['model']}"
763
956
  end
764
957
 
765
958
  # AGENT_COUNCIL_OPTS as UTF-8, or nil when unset. Retagged because ENV
@@ -787,7 +980,7 @@ module AgentCouncil
787
980
  -------------------------------------------------------------------------------
788
981
  Usage: agent-council [options] PROMPT_FILE [CONFIG_FILE]
789
982
  agent-council --consolidate RUN_DIR
790
- Repository: https://github.com/keithrbennett/agent-council
983
+ Repository: #{PROJECT_URL}
791
984
  Documentation (Local): #{File.join(PROJECT_ROOT, 'README.md')}
792
985
  Examples (Local): #{EXAMPLES_DIR}
793
986
  Version: #{VERSION}
@@ -825,6 +1018,16 @@ module AgentCouncil
825
1018
  exit 0
826
1019
  end
827
1020
 
1021
+ opts.on('--gem-dir', 'Show the root directory of the agent-council application and exit') do
1022
+ puts PROJECT_ROOT
1023
+ exit 0
1024
+ end
1025
+
1026
+ opts.on('--project-url', "Show the project's GitHub URL and exit") do
1027
+ puts PROJECT_URL
1028
+ exit 0
1029
+ end
1030
+
828
1031
  opts.separator ''
829
1032
  opts.separator 'Environment:'
830
1033
  opts.separator " #{ENV_OPTS_VAR} holds arguments inserted before the command-line ones,"
@@ -904,7 +1107,7 @@ module AgentCouncil
904
1107
  abort <<~MESSAGE
905
1108
  No config file given, and neither ./#{CWD_CONFIG_NAME} nor ~/#{HOME_CONFIG_NAME} exists.
906
1109
  Pass a config path: agent-council PROMPT_FILE CONFIG_FILE
907
- Minimal config: agents: [{provider: ..., model: ...}]
1110
+ Minimal config: agents: [{harness: pi, provider: ..., model: ...}]
908
1111
  Sample configs: #{File.join(EXAMPLES_DIR, 'configs')}
909
1112
  MESSAGE
910
1113
  end
@@ -941,22 +1144,21 @@ module AgentCouncil
941
1144
  abort "Config file must be a YAML mapping: #{config_path}" unless config.is_a?(Hash)
942
1145
 
943
1146
  agents = config['agents']
944
- abort "No agents defined in #{config_path}" unless agents.is_a?(Array) && !agents.empty?
945
- unless agents.all? { |a| valid_agent_entry?(a) }
946
- abort "Each agent in #{config_path} needs string 'provider' and 'model' fields"
1147
+ abort "No 'agents' list in #{config_path}" if agents.nil?
1148
+ unless agents.is_a?(Array)
1149
+ abort "'agents' in #{config_path} must be a list of entries, but is #{yaml_kind(agents)}"
947
1150
  end
948
-
1151
+ abort "'agents' in #{config_path} is an empty list; it needs at least one entry" if agents.empty?
949
1152
  consolidator = config['consolidator']
950
- if consolidator
951
- unless valid_agent_entry?(consolidator)
952
- abort "Consolidator in #{config_path} needs string 'provider' and 'model' fields"
953
- end
954
- unless File.file?(CONSOLIDATE_PROMPT_PATH)
955
- abort "Consolidator configured but template missing: #{CONSOLIDATE_PROMPT_PATH}"
956
- end
1153
+ entries = agents.each_with_index.to_h { |agent, i| ["'agents' entry ##{i + 1}", agent] }
1154
+ entries["'consolidator'"] = consolidator if consolidator
1155
+ abort_on_entry_errors(entries, config_path)
1156
+ if consolidator && !File.file?(CONSOLIDATE_PROMPT_PATH)
1157
+ abort "Consolidator configured but template missing: #{CONSOLIDATE_PROMPT_PATH}"
957
1158
  end
958
1159
 
959
- abort_unless_harness_installed
1160
+ # A consolidator of false, like nil, means none, as in the check above.
1161
+ abort_unless_harnesses_installed(consolidator ? [*agents, consolidator] : agents)
960
1162
 
961
1163
  # One run dir per invocation, day-bucketed so the reports dir stays
962
1164
  # navigable at volume: <reports dir>/<yyyy-mm-dd>/<hh-mm-ss>/. The dir name is pure time
@@ -995,9 +1197,10 @@ module AgentCouncil
995
1197
  # A default config's path is absolute (resolve_config_path makes it
996
1198
  # so), to show which of the defaults was picked up.
997
1199
  puts
998
- puts(argv[1] ? "Config: #{relative_path(config_path)}" : "Config: [default] #{config_path}")
999
- puts "Prompt: #{relative_path(prompt_path)}"
1000
- puts "Run Dir: #{relative_path(run_dir)}"
1200
+ puts "Working Dir: #{Dir.pwd}"
1201
+ puts(argv[1] ? "Config: #{relative_path(config_path)}" : "Config: [default] #{config_path}")
1202
+ puts "Prompt: #{relative_path(prompt_path)}"
1203
+ puts "Run Dir: #{relative_path(run_dir)}"
1001
1204
  puts "\nReview Agents (#{agents.size}):"
1002
1205
  agents.each_with_index do |agent, i|
1003
1206
  puts " ##{i + 1} #{agent_descriptor(agent)}"
@@ -1009,38 +1212,42 @@ module AgentCouncil
1009
1212
  agents.each_with_index do |agent, i|
1010
1213
  index = i + 1
1011
1214
  pool.start do
1012
- provider = agent.is_a?(Hash) ? agent['provider'] : nil
1013
- model = agent.is_a?(Hash) ? agent['model'] : nil
1014
1215
  meta = report_meta.merge('agent_index' => index)
1015
- (label, ok, detail, usage), elapsed = timed do
1216
+ (label, ok, detail, usage, warnings), elapsed = timed do
1016
1217
  run_agent(agent, analyst_prompt, reviews_dir, file_prefix,
1017
1218
  index: index,
1018
1219
  meta: meta,
1019
- header: ->(run_fields) { byline_table(meta.merge(run_fields), provider, model) },
1220
+ header: ->(run_fields) { byline_table(meta.merge(run_fields), agent) },
1020
1221
  pool: pool)
1021
1222
  end
1022
- [label, ok, detail, elapsed, usage]
1223
+ [label, ok, detail, elapsed, usage, warnings]
1023
1224
  end
1024
1225
  end
1025
- results = pool.collect do |label, ok, detail, elapsed|
1226
+ # Printed here, in the main thread, as everything is (see WorkerPool).
1227
+ results = pool.collect do |label, ok, detail, elapsed, _usage, warnings|
1026
1228
  duration = format_duration(elapsed)
1027
1229
  puts(ok ? " ✓ #{duration} #{label}" : " ✗ #{duration} #{label}\n #{detail}")
1230
+ puts warning_lines(warnings)
1028
1231
  end
1029
1232
 
1030
1233
  failed = results.count { |_, ok, _| !ok }
1031
1234
  puts "\nReviews (in #{relative_path(reviews_dir)}):"
1032
1235
  puts format_result_table(results)
1033
1236
  puts "\n--- Reviews complete (#{results.size - failed}/#{results.size} succeeded" \
1034
- "#{usage_summary(results.map(&:last))}) ---"
1237
+ "#{usage_summary(results.map { |_, _, _, _, usage| usage })}) ---"
1035
1238
  # Written now, so it's there even if the consolidation is interrupted.
1036
- analyst_runs = agents.zip(results).each_with_index.map do |(agent, (_, ok, detail, elapsed, usage)), i|
1037
- run_entry(agent, ok, detail, elapsed, usage, index: i + 1, dir: REVIEWS_DIR_NAME)
1239
+ analyst_runs = agents.zip(results).each_with_index.map do |(agent, result), i|
1240
+ _, ok, detail, elapsed, usage, warnings = result
1241
+ run_entry(agent, ok, detail, elapsed, usage, index: i + 1, dir: REVIEWS_DIR_NAME, warnings: warnings)
1038
1242
  end
1039
1243
  write_run_file(run_dir, analyst_runs, [])
1040
1244
 
1041
1245
  if consolidator
1042
1246
  puts "\nConsolidation Report (in #{relative_path(run_dir)}):"
1043
- failures = results.reject { |_, ok, _| ok }.map { |label, _, detail, _| [label, detail] }
1247
+ failures = agents.zip(results).reject { |_, (_, ok)| ok }.map do |agent, result|
1248
+ label, _, detail, _, _, warnings = result
1249
+ [label, failure_with_warnings(detail, warnings), Harnesses.name_of(agent)]
1250
+ end
1044
1251
  pool.start do
1045
1252
  timed do
1046
1253
  run_consolidation(consolidator, prompt, run_dir, file_prefix,
@@ -1048,9 +1255,10 @@ module AgentCouncil
1048
1255
  pool: pool)
1049
1256
  end
1050
1257
  end
1051
- (label, ok, detail, usage, meta_name), elapsed = pool.collect.first
1258
+ (label, ok, detail, usage, meta_name, warnings), elapsed = pool.collect.first
1052
1259
  puts format_result_table([[label, ok, detail, elapsed, usage]])
1053
- entry = run_entry(consolidator, ok, detail, elapsed, usage, meta_report: meta_name)
1260
+ puts warning_lines(warnings)
1261
+ entry = run_entry(consolidator, ok, detail, elapsed, usage, meta_report: meta_name, warnings: warnings)
1054
1262
  write_run_file(run_dir, analyst_runs, [entry])
1055
1263
  puts_consolidation_status(ok)
1056
1264
  end
@@ -1097,20 +1305,20 @@ module AgentCouncil
1097
1305
  end
1098
1306
  consolidator = config['consolidator'] if config.is_a?(Hash)
1099
1307
  abort "No consolidator in #{config_path}; add one to consolidate" unless consolidator
1100
- unless valid_agent_entry?(consolidator)
1101
- abort "Consolidator in #{config_path} needs string 'provider' and 'model' fields"
1102
- end
1308
+ abort_on_entry_errors({ "'consolidator'" => consolidator }, config_path,
1309
+ hint: "If this run predates the 'harness' key, its consolidator ran under pi: " \
1310
+ "add 'harness: pi' to the copy.")
1103
1311
  unless File.file?(CONSOLIDATE_PROMPT_PATH)
1104
1312
  abort "Consolidation template missing: #{CONSOLIDATE_PROMPT_PATH}"
1105
1313
  end
1106
1314
 
1107
1315
  file_prefix = "#{fields['run_stamp']}_#{fields['query']}" # as in a normal run
1108
- filename = consolidated_filename(file_prefix, consolidator['provider'], consolidator['model'])
1316
+ filename = consolidated_filename(file_prefix, consolidator)
1109
1317
  unless bare_name?(filename)
1110
1318
  abort "Invalid run_stamp or query in #{reviews_dir}: #{fields.values_at('run_stamp', 'query').inspect}"
1111
1319
  end
1112
1320
  names = [nil, 'findings', 'meta'].map do |part|
1113
- consolidated_filename(file_prefix, consolidator['provider'], consolidator['model'], part)
1321
+ consolidated_filename(file_prefix, consolidator, part)
1114
1322
  end
1115
1323
  existing = names.select { |name| File.exist?(File.join(run_dir, name)) }
1116
1324
  unless existing.empty?
@@ -1122,21 +1330,22 @@ module AgentCouncil
1122
1330
  prompt = File.read(prompt_path, encoding: ENCODING)
1123
1331
  abort "Prompt copy is empty: #{prompt_path}" if prompt.empty?
1124
1332
 
1125
- abort_unless_harness_installed
1333
+ abort_unless_harnesses_installed([consolidator])
1126
1334
 
1127
1335
  # In the same key order as a normal run's front matter.
1128
1336
  meta = fields.slice('role', 'timestamp', 'query', 'prompt_file', 'config_file', 'config_source',
1129
1337
  'run_stamp')
1130
1338
  meta['timestamp'] = iso_timestamp(meta['timestamp']) if meta['timestamp'].is_a?(Time)
1131
1339
 
1132
- puts "Config: #{relative_path(config_path)}"
1133
- puts "Prompt: #{relative_path(prompt_path)}"
1134
- puts "Run Dir: #{relative_path(run_dir)}"
1340
+ puts "Working Dir: #{Dir.pwd}"
1341
+ puts "Config: #{relative_path(config_path)}"
1342
+ puts "Prompt: #{relative_path(prompt_path)}"
1343
+ puts "Run Dir: #{relative_path(run_dir)}"
1135
1344
  puts "\nConsolidator Agent:\n #{agent_descriptor(consolidator)}"
1136
1345
  puts "\nConsolidation Report (in #{relative_path(run_dir)}, " \
1137
1346
  "from #{reports.size} review#{'s' unless reports.size == 1}):"
1138
- failures = missing_agents(config, reports)
1139
1347
  analysts, consolidations = read_run_file(run_dir)
1348
+ failures = missing_agents(config, reports, analysts)
1140
1349
  pool = WorkerPool.new(grace: INTERRUPT_GRACE_SECONDS)
1141
1350
  pool.trap_signals
1142
1351
  pool.start do
@@ -1146,16 +1355,18 @@ module AgentCouncil
1146
1355
  analyst_runs: analysts || [], pool: pool)
1147
1356
  end
1148
1357
  end
1149
- (label, ok, detail, usage, meta_name), elapsed = pool.collect.first
1358
+ (label, ok, detail, usage, meta_name, warnings), elapsed = pool.collect.first
1150
1359
  puts format_result_table([[label, ok, detail, elapsed, usage]])
1360
+ puts warning_lines(warnings)
1151
1361
  # Added to the run's run.json. Without one (deleted, or unreadable),
1152
1362
  # none is written: a total covering only this consolidation would
1153
1363
  # pass for the run's.
1154
1364
  if analysts
1155
- entry = run_entry(consolidator, ok, detail, elapsed, usage, meta_report: meta_name)
1365
+ entry = run_entry(consolidator, ok, detail, elapsed, usage, meta_report: meta_name, warnings: warnings)
1156
1366
  write_run_file(run_dir, analysts, consolidations + [entry])
1157
1367
  else
1158
- warn "No readable #{RUN_FILENAME} in #{relative_path(run_dir)}; not recording this consolidation's run"
1368
+ warn "No readable #{RUN_FILENAME} in #{relative_path(run_dir)}, " \
1369
+ "so this consolidation won't be recorded in one"
1159
1370
  end
1160
1371
  puts_consolidation_status(ok)
1161
1372
  exit(ok ? 0 : 1)
@@ -1173,30 +1384,62 @@ module AgentCouncil
1173
1384
  File.basename(name) == name
1174
1385
  end
1175
1386
 
1176
- # What --consolidate tells the consolidator about an agent without a report.
1387
+ # A failed agent's reason as the consolidator is told it: its error, then
1388
+ # any warnings about the agent, since they may be why it failed.
1389
+ module_function def failure_with_warnings(detail, warnings)
1390
+ [detail, *Array(warnings).map { |warning| "warning: #{warning}" }].join('; ')
1391
+ end
1392
+
1393
+ # What --consolidate tells the consolidator about an agent without a
1394
+ # report when run.json doesn't record that it failed.
1177
1395
  MISSING_REPORT_REASON =
1178
1396
  'reason not recorded (it may have failed, been interrupted, or had its report removed)'
1179
1397
 
1180
1398
  # For --consolidate: the config copy's agents that have no report, as
1181
- # [label, reason] pairs. Why wasn't recorded, and needn't be a failure:
1182
- # the run may have been interrupted, or a report removed.
1183
- module_function def missing_agents(config, reports)
1399
+ # [label, reason, harness] triples, as a run tells its consolidator. The
1400
+ # reason is the error and warnings run.json records for the agent's
1401
+ # failure (analyst_runs: its analyst entries); else it isn't known,
1402
+ # and needn't be a failure: the run may have been interrupted, or a
1403
+ # report removed. An agent the config copy gives an unknown harness is
1404
+ # still listed: it needs no harness to be labeled, and the config may
1405
+ # come from a newer version.
1406
+ module_function def missing_agents(config, reports, analyst_runs = [])
1184
1407
  agents = config['agents'].is_a?(Array) ? config['agents'] : []
1185
1408
  present = reports.map(&:first)
1186
1409
  agents.each_with_index.filter_map do |agent, i|
1187
- next unless valid_agent_entry?(agent)
1410
+ next unless labelable_entry?(agent)
1188
1411
 
1189
1412
  label = agent_label(agent['provider'], agent['model'], i + 1)
1190
- [label, MISSING_REPORT_REASON] unless present.include?(label)
1413
+ next if present.include?(label)
1414
+
1415
+ [label, recorded_failure(agent, i + 1, analyst_runs) || MISSING_REPORT_REASON, Harnesses.name_of(agent)]
1191
1416
  end
1192
1417
  end
1193
1418
 
1194
- # Checked up front, before any run dir is created or model called.
1195
- module_function def abort_unless_harness_installed
1196
- return if executable_on_path?(HARNESS::NAME)
1419
+ # The reason run.json records for the failure of agent (the config
1420
+ # entry at 1-based index), with its warnings, or nil if none is recorded.
1421
+ module_function def recorded_failure(agent, index, analyst_runs)
1422
+ run = Array(analyst_runs).find do |entry|
1423
+ entry.is_a?(Hash) && entry['agent_index'] == index && entry['ok'] == false &&
1424
+ entry.values_at('provider', 'model') == agent.values_at('provider', 'model') &&
1425
+ Harnesses.name_of(entry) == Harnesses.name_of(agent)
1426
+ end
1427
+ return nil unless run && run['error'].is_a?(String)
1428
+
1429
+ failure_with_warnings(run['error'], Array(run['warnings']).grep(String))
1430
+ end
1431
+
1432
+ # Checked up front, before any run dir is created or model called: the
1433
+ # executable of every harness the config entries use (validated ones, so
1434
+ # each harness is known).
1435
+ module_function def abort_unless_harnesses_installed(entries)
1436
+ names = entries.map { |entry| Harnesses.module_for(entry)::NAME }.uniq
1437
+ missing = names.reject { |name| executable_on_path?(name) }
1438
+ return if missing.empty?
1197
1439
 
1440
+ lines = missing.map { |name| "#{name} executable not found; is `#{name}` installed and on your PATH?" }
1198
1441
  abort <<~MESSAGE
1199
- #{HARNESS::NAME} executable not found; is `#{HARNESS::NAME}` installed and on your PATH?
1442
+ #{lines.join("\n")}
1200
1443
  See "Prerequisites" in #{File.join(PROJECT_ROOT, 'README.md')}
1201
1444
  MESSAGE
1202
1445
  end