agent-council 0.1.0 → 0.3.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 and Codex ignore 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,127 @@ 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, or errors it hit without failing (see
240
+ # ClaudeCodeHarness.warnings and CodexHarness.warnings), which a report
241
+ # may lack, or which may be why the agent failed. Advisory only: failing to read them
242
+ # must not fail an agent whose report is saved, so that becomes a warning
243
+ # too.
244
+ # Each is a plain_line, so wherever it goes (console, report, run.json,
245
+ # and so anything that prints run.json's values) it can't carry a
246
+ # terminal escape from a command the model wrote.
247
+ module_function def run_warnings(harness, stdout)
248
+ # An Array, by the harness contract; nil tolerated.
249
+ Array(harness.warnings(stdout)).map { |warning| plain_line(warning) }
250
+ rescue => e
251
+ [plain_line("could not read the agent's warnings (#{e.class}: #{e.message})")]
252
+ end
253
+
254
+ # A harness's reason for a failure, as run_agent reports it: a
255
+ # plain_line, since it can quote the model or the CLI, cut to 300
256
+ # characters plus "..." so it doesn't swamp the progress line, the Errors
257
+ # list, or the consolidation prompt; 'no error output' if nothing is left.
258
+ module_function def failure_reason(text)
259
+ reason = plain_line(text)
260
+ return 'no error output' if reason.empty?
261
+
262
+ reason.length > 300 ? "#{reason[0, 300]}..." : reason
263
+ end
264
+
265
+ # Lines showing an agent's warnings under its progress line or result table.
266
+ module_function def warning_lines(warnings)
267
+ Array(warnings).map { |warning| " Warning: #{plain_line(warning)}" }
268
+ end
269
+
270
+ # Text on one line with no control characters: every run of whitespace
271
+ # or control characters (newlines, carriage returns, the ESC that starts
272
+ # a terminal escape sequence) becomes one space; the rest of an escape
273
+ # sequence, such as "[2J", stays as harmless text. Warnings can quote a
274
+ # model's refused command, so this keeps one from moving the cursor or
275
+ # clearing the screen when printed, or from breaking the line it appears
276
+ # on in a report. Text in any encoding is read as UTF-8 (a SystemCallError's
277
+ # message can be binary). Invisible format characters (Unicode category Cf, such
278
+ # as bidirectional overrides and zero-width spaces) are removed, so text
279
+ # can't display reordered or hide characters. Invalid bytes become U+FFFD,
280
+ # since this also runs in rescue clauses and must not raise.
281
+ module_function def plain_line(text)
282
+ # Alternation, not one bracket class: the two overlap, which ruby -w
283
+ # warns of.
284
+ String.new(text.to_s, encoding: ENCODING).scrub.gsub(/\p{Cf}/, '')
285
+ .gsub(/(?:[[:space:]]|[[:cntrl:]])+/, ' ').strip
286
+ end
287
+
213
288
  # Creates a new run dir in day_dir and returns its name: base, or base-2,
214
289
  # base-3, ... if that is taken. Dir.mkdir fails if the dir exists, so the
215
290
  # claim is atomic: runs started in the same second (or whose local time
@@ -294,15 +369,17 @@ module AgentCouncil
294
369
 
295
370
  # The consolidator's substantive prompt: the instructions template, the
296
371
  # 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.
372
+ # labels, and the agents without a report, as [label, reason, harness]
373
+ # triples; the consolidator can't otherwise know about those.
299
374
  module_function def consolidation_prompt(original_prompt, reports, failures = [])
300
375
  template = File.read(CONSOLIDATE_PROMPT_PATH, encoding: ENCODING)
301
376
  body = reports.map do |label, text, fields|
302
- harness = (fields && fields['harness']) || HARNESS::NAME
303
- "## Report from #{label}\n\nHarness: #{harness}\n\n#{text}"
377
+ "## Report from #{label}\n\nHarness: #{Harnesses.name_of(fields)}\n\n#{text}"
304
378
  end.join("\n\n---\n\n")
305
- failed = failures.empty? ? 'None.' : failures.map { |label, reason| "- #{label}: #{reason}" }.join("\n")
379
+ failed = failures.map do |label, reason, harness|
380
+ "- #{label}#{" (harness: #{plain_line(harness)})" if harness}: #{plain_line(reason)}"
381
+ end
382
+ failed = failures.empty? ? 'None.' : failed.join("\n")
306
383
  <<~MARKDOWN
307
384
  #{template}
308
385
 
@@ -330,9 +407,11 @@ module AgentCouncil
330
407
  # dir, and stays self-describing when copied out of the tree.
331
408
  # part: 'findings' or 'meta' for the files a consolidated report is split
332
409
  # into (see split_consolidated_report); none for the report as written.
333
- module_function def consolidated_filename(file_prefix, provider, model, part = nil)
410
+ # consolidator: its config entry.
411
+ module_function def consolidated_filename(file_prefix, consolidator, part = nil)
334
412
  suffix = part ? "_#{part}" : ''
335
- "#{file_prefix}_consolidated_#{HARNESS::NAME}_#{sanitize(provider)}_#{sanitize(model)}#{suffix}.md"
413
+ names = consolidator.values_at('provider', 'model').map { |name| sanitize(name) }
414
+ "#{file_prefix}_consolidated_#{[Harnesses.name_of(consolidator), *names].join('_')}#{suffix}.md"
336
415
  end
337
416
 
338
417
  # The line the consolidator is asked to write between its findings and
@@ -343,7 +422,7 @@ module AgentCouncil
343
422
  # <model>", for the findings file's legend.
344
423
  module_function def full_label(fields)
345
424
  index = fields['agent_index']
346
- parts = [fields['harness'] || HARNESS::NAME, fields['provider'], fields['model']].join(' / ')
425
+ parts = [Harnesses.name_of(fields), fields['provider'], fields['model']].join(' / ')
347
426
  index ? "##{index} #{parts}" : parts
348
427
  end
349
428
 
@@ -395,13 +474,14 @@ module AgentCouncil
395
474
  # identifying the run, for its top. Returns the findings filename and the
396
475
  # meta filename, or, if the report can't be split or the split files
397
476
  # 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')
477
+ # consolidated_filename) and nil, with a warning. consolidator: its
478
+ # config entry, which names the split files.
479
+ module_function def split_consolidated_report(run_dir, filename, file_prefix, consolidator, head, labels,
480
+ info = [])
404
481
  written = []
482
+ path = File.join(run_dir, filename)
483
+ unsplit_name = consolidated_filename(file_prefix, consolidator)
484
+ findings_name = consolidated_filename(file_prefix, consolidator, 'findings')
405
485
  content = File.read(path, encoding: ENCODING)
406
486
  front = content[/\A---\n.+?\n---\n\n?/m] || ''
407
487
  body = content.delete_prefix(front)
@@ -435,8 +515,12 @@ module AgentCouncil
435
515
  File.rename(temp, path)
436
516
  [findings_name, filename]
437
517
  rescue => e
438
- # A failed split must not fail the consolidation, whose model run is
439
- # already paid for and whose report is intact.
518
+ # A failed split must not fail the consolidation, whose model call is
519
+ # already paid for and whose report is intact. Without an unsplit name
520
+ # (a consolidator entry that can't name a file, which validation rules
521
+ # out), there is nothing to fall back to, so the error is raised as is.
522
+ raise unless unsplit_name
523
+
440
524
  warn "Could not split #{relative_path(path)}: #{e.message}"
441
525
  written.each { |name| FileUtils.rm_f(File.join(run_dir, name)) }
442
526
  keep_unsplit(run_dir, filename, unsplit_name)
@@ -459,23 +543,24 @@ module AgentCouncil
459
543
  [filename, nil]
460
544
  end
461
545
 
462
- # Markdown table of the report's main front-matter fields and its run's
546
+ # Markdown table of the report's main front-matter fields and the agent's
463
547
  # 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)
548
+ # reports, followed by sources_table). agent: the agent's config entry.
549
+ module_function def byline_table(meta, agent)
466
550
  fields = {
467
551
  'role' => meta['role'],
468
552
  'agent' => (meta['agent_index'] ? "##{meta['agent_index']}" : nil),
469
553
  'query' => meta['query'],
470
- 'harness' => HARNESS::NAME,
471
- 'provider' => provider,
472
- 'model' => model,
554
+ 'harness' => Harnesses.name_of(agent),
555
+ 'provider' => agent['provider'],
556
+ 'model' => agent['model'],
473
557
  'timestamp' => meta['timestamp'],
474
558
  'consolidated_at' => meta['consolidated_at'],
475
559
  'duration' => meta['duration'],
476
560
  'usage' => format_usage(meta['usage']),
561
+ 'warnings' => (Array(meta['warnings']).join('; ') unless Array(meta['warnings']).empty?),
477
562
  }.compact
478
- rows = fields.map { |field, value| "| #{field} | #{value} |" }
563
+ rows = fields.map { |field, value| "| #{field} | #{table_cell(value)} |" }
479
564
  <<~TABLE
480
565
  | Field | Value |
481
566
  | :-------- | :---------------------------- |
@@ -483,8 +568,15 @@ module AgentCouncil
483
568
  TABLE
484
569
  end
485
570
 
571
+ # A value as one Markdown table cell: a plain_line, with its pipes and
572
+ # backslashes escaped, so text such as a refused `a | b` or `grep '\|'`
573
+ # command can't add columns or rows.
574
+ module_function def table_cell(value)
575
+ plain_line(value).gsub(/[\\|]/) { |char| "\\#{char}" }
576
+ end
577
+
486
578
  # 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 =>
579
+ # sources, with that agent's duration and usage from source_runs (label =>
488
580
  # run.json entry); - where unknown. Input counts cached input too.
489
581
  module_function def sources_table(sources, source_runs)
490
582
  rows = sources.map do |label|
@@ -503,10 +595,11 @@ module AgentCouncil
503
595
  end
504
596
 
505
597
  # 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
598
+ # its report into the same run dir. Returns [label, ok, detail, usage,
599
+ # meta_name, warnings], as run_agent does with meta_name inserted:
507
600
  # 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.
601
+ # split_consolidated_report), and meta_name the meta file's (nil when
602
+ # unsplit or failed); never raises.
510
603
  # analyst_runs: the run's run.json analyst entries, for the sources
511
604
  # table's durations and usage. failures: as for consolidation_prompt.
512
605
  # pool: as for run_agent.
@@ -514,12 +607,14 @@ module AgentCouncil
514
607
  meta: {}, prompt_path: nil, failures: [], analyst_runs: [], pool: nil)
515
608
  provider = consolidator['provider'] if consolidator.is_a?(Hash)
516
609
  model = consolidator['model'] if consolidator.is_a?(Hash)
517
- return ['consolidator', false, "config entry needs 'provider' and 'model'"] if provider.nil? || model.nil?
610
+ if (error = entry_error(consolidator))
611
+ return ['consolidator', false, "config entry #{error}", nil, nil, []]
612
+ end
518
613
 
519
614
  reports = collect_reports(File.join(run_dir, REVIEWS_DIR_NAME))
520
615
  if reports.empty?
521
616
  return [agent_label(provider, model), false,
522
- "no reports found in #{relative_path(File.join(run_dir, REVIEWS_DIR_NAME))}"]
617
+ "no reports found in #{relative_path(File.join(run_dir, REVIEWS_DIR_NAME))}", nil, nil, []]
523
618
  end
524
619
 
525
620
  prompt = consolidation_prompt(original_prompt, reports, failures)
@@ -532,25 +627,27 @@ module AgentCouncil
532
627
  prompt_line = prompt_path ? "### Prompt: #{prompt_path}\n\n" : ''
533
628
  head = nil
534
629
  header = ->(run_fields) do
535
- head = "# Consolidated Report\n\n#{prompt_line}#{byline_table(meta.merge(run_fields), provider,
536
- model)}\n" \
630
+ head = "# Consolidated Report\n\n#{prompt_line}" \
631
+ "#{byline_table(meta.merge(run_fields), consolidator)}\n" \
537
632
  "#{sources_table(meta['sources'], source_runs)}"
538
633
  end
539
- label, ok, detail, usage = run_agent(consolidator, prompt, run_dir, file_prefix,
540
- filename: consolidated_filename(file_prefix, provider, model, 'meta'),
634
+ label, ok, detail, usage, warnings = run_agent(consolidator, prompt, run_dir, file_prefix,
635
+ filename: consolidated_filename(file_prefix, consolidator, 'meta'),
541
636
  header: header,
542
637
  meta: meta,
543
638
  pool: pool)
639
+ warnings = Array(warnings)
544
640
  if ok
545
641
  labels = reports.map { |_, _, fields| full_label(fields) }
546
642
  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)
643
+ "Consolidated by: #{agent_descriptor(consolidator)}, #{meta['consolidated_at']}",
644
+ ("Consolidator warnings: #{plain_line(warnings.join('; '))}" unless warnings.empty?)].compact
645
+ detail, meta_name = split_consolidated_report(run_dir, detail, file_prefix, consolidator, head, labels,
646
+ info)
550
647
  end
551
- [label, ok, detail, usage, meta_name]
648
+ [label, ok, detail, usage, meta_name, warnings]
552
649
  rescue => e
553
- [agent_label(provider, model), false, "#{e.class}: #{e.message}"]
650
+ [agent_label(provider, model), false, failure_reason("#{e.class}: #{e.message}"), nil, nil, []]
554
651
  end
555
652
 
556
653
  module_function def relative_path(path)
@@ -572,7 +669,7 @@ module AgentCouncil
572
669
  format('%02d:%02d:%02d', total / 3600, total % 3600 / 60, total % 60)
573
670
  end
574
671
 
575
- # Token usage (see HARNESS) as e.g. "1.2M in (900.0k cached) / 30.5k out,
672
+ # Token usage (see Harnesses) as e.g. "1.2M in (900.0k cached) / 30.5k out,
576
673
  # $0.85", where "in" counts all input, cached or not. The cost is left out
577
674
  # when unknown. nil for nil usage.
578
675
  module_function def format_usage(usage)
@@ -593,7 +690,7 @@ module AgentCouncil
593
690
  end
594
691
 
595
692
  # [input (cached or not), cached input, output, cost (nil when unknown)]
596
- # from a usage hash (see HARNESS), or nil for unknown usage.
693
+ # from a usage hash (see Harnesses), or nil for unknown usage.
597
694
  module_function def usage_figures(usage)
598
695
  return nil unless usage.is_a?(Hash)
599
696
 
@@ -613,7 +710,7 @@ module AgentCouncil
613
710
  dollars < 0.01 ? '<$0.01' : format('$%.2f', dollars)
614
711
  end
615
712
 
616
- # The sum of usage hashes (see HARNESS), ignoring nils (and anything else
713
+ # The sum of usage hashes (see Harnesses), ignoring nils (and anything else
617
714
  # not a hash); nil if there are none.
618
715
  # The cost is summed only if every usage has one, so a partial total
619
716
  # isn't presented as the whole.
@@ -626,32 +723,46 @@ module AgentCouncil
626
723
  costs.all?(Numeric) ? total.merge('cost' => costs.sum.round(6)) : total
627
724
  end
628
725
 
629
- # The run dir's machine-readable record of its agents' runs.
726
+ # The summed cost of the usages whose cost is known, and how many those
727
+ # are, for when sum_usage leaves the cost out because some are unknown
728
+ # (e.g. a Codex agent's, which Codex doesn't price). [nil, 0] if none is.
729
+ module_function def known_cost(usages)
730
+ costs = usages.grep(Hash).map { |u| u['cost'] }.grep(Numeric)
731
+ [costs.empty? ? nil : costs.sum.round(6), costs.size]
732
+ end
733
+
734
+ # The run dir's machine-readable record of its analysts and consolidations.
630
735
  RUN_FILENAME = 'run.json'
631
736
 
632
737
  # A run.json entry for an agent's run_agent result and its elapsed
633
738
  # seconds: its report's path under dir (the run dir's reviews_dir for
634
739
  # 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
740
+ # so a run can mix harnesses. meta_report: for a
636
741
  # 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'],
742
+ # name), the other file, which carries the front matter. warnings: the
743
+ # agent's warnings (see run_agent), recorded only if there are any.
744
+ module_function def run_entry(agent, ok, detail, elapsed, usage, index: nil, dir: nil, meta_report: nil,
745
+ warnings: nil)
746
+ entry = { 'agent_index' => index, 'harness' => Harnesses.name_of(agent), 'provider' => agent['provider'],
640
747
  'model' => agent['model'], 'ok' => ok }.compact
641
748
  entry[ok ? 'report' : 'error'] = ok && dir ? File.join(dir, detail) : detail
642
749
  entry['meta_report'] = (dir ? File.join(dir, meta_report) : meta_report) if ok && meta_report
750
+ entry['warnings'] = warnings if warnings.is_a?(Array) && !warnings.empty?
643
751
  entry.merge('duration_seconds' => elapsed.round(1), 'usage' => usage)
644
752
  end
645
753
 
646
754
  # 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
648
- # (those that reported usage). Replaced atomically, so a
755
+ # entry (see run_entry), their total usage, how many entries it covers
756
+ # (those that reported usage), and the summed cost of the entries whose
757
+ # cost is known, with how many they are (see known_cost). Replaced atomically, so a
649
758
  # reader or a Ctrl-C never sees it half written. A failure to write it is
650
759
  # only warned about: the reports are what matter.
651
760
  module_function def write_run_file(run_dir, analysts, consolidations)
652
761
  usages = (analysts + consolidations).map { |entry| entry['usage'] }
762
+ cost, cost_runs = known_cost(usages)
653
763
  data = { 'analysts' => analysts, 'consolidations' => consolidations,
654
- 'total_usage' => sum_usage(usages), 'total_usage_runs' => usages.grep(Hash).size }
764
+ 'total_usage' => sum_usage(usages), 'total_usage_runs' => usages.grep(Hash).size,
765
+ 'known_cost' => cost, 'known_cost_runs' => cost_runs }
655
766
  path = File.join(run_dir, RUN_FILENAME)
656
767
  temp = "#{path}.#{Process.pid}.tmp"
657
768
  File.write(temp, "#{JSON.pretty_generate(data)}\n")
@@ -683,9 +794,10 @@ module AgentCouncil
683
794
  RIGHT_ALIGNED_COLUMNS = (3..6)
684
795
 
685
796
  # 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
797
+ # results (any further elements, such as warnings, are ignored): a
798
+ # heading row, then one row per result, with ✓ or ✗ and its usage (as
799
+ # for usage_cells), then the failures' errors, if any, listed below the
800
+ # table so long messages don't widen it. Report filenames
689
801
  # aren't shown: an analyst's is found by its agent number, and the
690
802
  # consolidated report is at the run dir's top level.
691
803
  module_function def format_result_table(results)
@@ -705,14 +817,21 @@ module AgentCouncil
705
817
  errors.empty? ? lines : [*lines, '', ' Errors:', *errors]
706
818
  end
707
819
 
708
- # "; <total usage>" for a summary line, noting how many of the runs it
709
- # covers when some reported no usage; "" when none reported any.
820
+ # "; <total usage>" for a summary line, noting how many of the agents it
821
+ # covers when some reported no usage; "" when none reported any. When
822
+ # only some agents' cost is known, the total leaves the cost out, so the
823
+ # known agents' cost follows, with how many they are.
710
824
  module_function def usage_summary(usages)
711
- total = format_usage(sum_usage(usages))
825
+ sum = sum_usage(usages)
826
+ total = format_usage(sum)
712
827
  return '' unless total
713
828
 
714
829
  reported = usages.grep(Hash).size
715
- "; #{total}#{" (from #{reported} of #{usages.size} agents)" if reported < usages.size}"
830
+ text = "; #{total}#{" (from #{reported} of #{usages.size} agents)" if reported < usages.size}"
831
+ cost, cost_runs = known_cost(usages)
832
+ return text if sum.key?('cost') || cost.nil? || !cost.positive?
833
+
834
+ "#{text}; #{format_cost(cost)} for the #{cost_runs} of #{usages.size} agents with a known cost"
716
835
  end
717
836
 
718
837
  # East Asian wide and fullwidth characters (CJK, Hangul, fullwidth forms,
@@ -738,12 +857,105 @@ module AgentCouncil
738
857
  puts "\n--- Consolidation #{ok ? 'complete' : 'error'} ---"
739
858
  end
740
859
 
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)
860
+ # True if a config entry (agent or consolidator) has the string 'provider'
861
+ # and 'model' fields its label is made from.
862
+ module_function def labelable_entry?(entry)
744
863
  entry.is_a?(Hash) && entry['provider'].is_a?(String) && entry['model'].is_a?(String)
745
864
  end
746
865
 
866
+ # The keys every config entry (agent or consolidator) must give, each a
867
+ # nonblank string. None has a default: a default harness or provider
868
+ # would go stale as harnesses change, so a config says what it runs.
869
+ ENTRY_KEYS = %w[harness provider model].freeze
870
+
871
+ # What kind of YAML value a value is, for error messages.
872
+ module_function def yaml_kind(value)
873
+ case value
874
+ when Hash then 'a mapping'
875
+ when Array then 'a list'
876
+ when String then 'a string'
877
+ when nil then 'null'
878
+ when true, false then 'a boolean'
879
+ when Numeric then 'a number'
880
+ else "a #{value.class.name.downcase}" # unreachable from safe_load, which rejects dates
881
+ end
882
+ end
883
+
884
+ # 'a', 'a' and 'b', 'a', 'b', and 'c': names quoted and joined.
885
+ module_function def quoted_list(names)
886
+ quoted = names.map { |name| "'#{name}'" }
887
+ quoted.size < 3 ? quoted.join(' and ') : "#{quoted[0..-2].join(', ')}, and #{quoted.last}"
888
+ end
889
+
890
+ # Why a config entry can't be run, as a phrase following the entry's
891
+ # name, or nil if it can: it must be a mapping giving each of ENTRY_KEYS
892
+ # as a nonblank string, and its harness must be a known one. Every
893
+ # problem is named, so one edit can fix them all.
894
+ module_function def entry_error(entry)
895
+ known = Harnesses::BY_NAME.keys
896
+ return "must be a mapping giving #{entry_needs}, but is #{yaml_kind(entry)}" unless entry.is_a?(Hash)
897
+
898
+ missing = ENTRY_KEYS.select { |key| entry[key].nil? }
899
+ blank = ENTRY_KEYS.select { |key| entry[key].is_a?(String) && blank_value?(entry[key]) }
900
+ non_strings = ENTRY_KEYS.reject { |key| entry[key].nil? || entry[key].is_a?(String) }
901
+ problems = []
902
+ problems << "is missing #{quoted_list(missing)}" unless missing.empty?
903
+ unless blank.empty?
904
+ problems << "gives #{blank.size == 1 ? 'a blank' : 'blank values for'} #{quoted_list(blank)}"
905
+ end
906
+ non_strings.each do |key|
907
+ value = entry[key]
908
+ # Quoting fixes a scalar YAML read as a number, date, or boolean, but
909
+ # no quoted value but a known name makes a harness valid.
910
+ fix =
911
+ if key == 'harness' then " (known: #{known.join(', ')})"
912
+ elsif !value.is_a?(Hash) && !value.is_a?(Array) then ' (quote it)'
913
+ end
914
+ problems << "gives '#{key}' as #{yaml_kind(value)}, #{value.inspect}, not a string#{fix}"
915
+ end
916
+ harness = entry['harness']
917
+ if harness.is_a?(String) && !blank_value?(harness) && !known.include?(harness)
918
+ problems << "names an unknown harness, #{harness.inspect} (known: #{known.join(', ')})"
919
+ end
920
+ return if problems.empty?
921
+
922
+ problems.join('; ')
923
+ end
924
+
925
+ # The keys every entry gives, with the known harnesses.
926
+ module_function def entry_needs
927
+ "#{quoted_list(ENTRY_KEYS)} (harness: #{Harnesses::BY_NAME.keys.join(', ')})"
928
+ end
929
+
930
+ # True if a config value counts as missing: absent, null, or blank.
931
+ module_function def blank_value?(value)
932
+ value.nil? || (value.is_a?(String) && value.strip.empty?)
933
+ end
934
+
935
+ # Added after the errors when an entry gives no harness, which may be
936
+ # one from a 0.1.0 config, when every entry ran under pi.
937
+ MISSING_HARNESS_HINT =
938
+ "If this is a 0.1.0 config, it ran every entry under pi: add 'harness: pi' to each entry."
939
+
940
+ # Aborts, if any of entries (a Hash of name, e.g. "'agents' entry #2", to
941
+ # config entry) has an error, with one line per bad entry, naming the
942
+ # config file, so one edit can fix them all. When a bad entry is a
943
+ # mapping without a harness, a line saying what every entry needs
944
+ # follows, and then hint, if no entry gives a harness (as in a 0.1.0
945
+ # config; a config that names some may have a typo instead).
946
+ module_function def abort_on_entry_errors(entries, config_path, hint: MISSING_HARNESS_HINT)
947
+ bad = entries.filter_map { |name, entry| (error = entry_error(entry)) && [name, entry, error] }
948
+ return if bad.empty?
949
+
950
+ lines = bad.map { |name, _entry, error| "#{name} in #{config_path} #{error}" }
951
+ harnessless = ->(entry) { entry.is_a?(Hash) && blank_value?(entry['harness']) }
952
+ if bad.any? { |_name, entry, _error| harnessless.(entry) }
953
+ lines << "Every entry needs #{entry_needs}."
954
+ lines << hint if entries.values.all?(&harnessless)
955
+ end
956
+ abort lines.join("\n")
957
+ end
958
+
747
959
  # True if `name` (a bare command name) is an executable file in a PATH
748
960
  # directory. Checked up front so a missing harness fails before any run
749
961
  # dir is created, rather than as an Errno::ENOENT from every agent. An
@@ -759,7 +971,7 @@ module AgentCouncil
759
971
  # "harness / provider / model" for a validated config entry, printed at
760
972
  # startup so it is clear which agents are still running later.
761
973
  module_function def agent_descriptor(entry)
762
- "#{HARNESS::NAME} / #{entry['provider']} / #{entry['model']}"
974
+ "#{Harnesses.name_of(entry)} / #{entry['provider']} / #{entry['model']}"
763
975
  end
764
976
 
765
977
  # AGENT_COUNCIL_OPTS as UTF-8, or nil when unset. Retagged because ENV
@@ -787,7 +999,7 @@ module AgentCouncil
787
999
  -------------------------------------------------------------------------------
788
1000
  Usage: agent-council [options] PROMPT_FILE [CONFIG_FILE]
789
1001
  agent-council --consolidate RUN_DIR
790
- Repository: https://github.com/keithrbennett/agent-council
1002
+ Repository: #{PROJECT_URL}
791
1003
  Documentation (Local): #{File.join(PROJECT_ROOT, 'README.md')}
792
1004
  Examples (Local): #{EXAMPLES_DIR}
793
1005
  Version: #{VERSION}
@@ -825,6 +1037,16 @@ module AgentCouncil
825
1037
  exit 0
826
1038
  end
827
1039
 
1040
+ opts.on('--gem-dir', 'Show the root directory of the agent-council application and exit') do
1041
+ puts PROJECT_ROOT
1042
+ exit 0
1043
+ end
1044
+
1045
+ opts.on('--project-url', "Show the project's GitHub URL and exit") do
1046
+ puts PROJECT_URL
1047
+ exit 0
1048
+ end
1049
+
828
1050
  opts.separator ''
829
1051
  opts.separator 'Environment:'
830
1052
  opts.separator " #{ENV_OPTS_VAR} holds arguments inserted before the command-line ones,"
@@ -904,7 +1126,7 @@ module AgentCouncil
904
1126
  abort <<~MESSAGE
905
1127
  No config file given, and neither ./#{CWD_CONFIG_NAME} nor ~/#{HOME_CONFIG_NAME} exists.
906
1128
  Pass a config path: agent-council PROMPT_FILE CONFIG_FILE
907
- Minimal config: agents: [{provider: ..., model: ...}]
1129
+ Minimal config: agents: [{harness: pi, provider: ..., model: ...}]
908
1130
  Sample configs: #{File.join(EXAMPLES_DIR, 'configs')}
909
1131
  MESSAGE
910
1132
  end
@@ -941,22 +1163,21 @@ module AgentCouncil
941
1163
  abort "Config file must be a YAML mapping: #{config_path}" unless config.is_a?(Hash)
942
1164
 
943
1165
  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"
1166
+ abort "No 'agents' list in #{config_path}" if agents.nil?
1167
+ unless agents.is_a?(Array)
1168
+ abort "'agents' in #{config_path} must be a list of entries, but is #{yaml_kind(agents)}"
947
1169
  end
948
-
1170
+ abort "'agents' in #{config_path} is an empty list; it needs at least one entry" if agents.empty?
949
1171
  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
1172
+ entries = agents.each_with_index.to_h { |agent, i| ["'agents' entry ##{i + 1}", agent] }
1173
+ entries["'consolidator'"] = consolidator if consolidator
1174
+ abort_on_entry_errors(entries, config_path)
1175
+ if consolidator && !File.file?(CONSOLIDATE_PROMPT_PATH)
1176
+ abort "Consolidator configured but template missing: #{CONSOLIDATE_PROMPT_PATH}"
957
1177
  end
958
1178
 
959
- abort_unless_harness_installed
1179
+ # A consolidator of false, like nil, means none, as in the check above.
1180
+ abort_unless_harnesses_installed(consolidator ? [*agents, consolidator] : agents)
960
1181
 
961
1182
  # One run dir per invocation, day-bucketed so the reports dir stays
962
1183
  # navigable at volume: <reports dir>/<yyyy-mm-dd>/<hh-mm-ss>/. The dir name is pure time
@@ -995,9 +1216,10 @@ module AgentCouncil
995
1216
  # A default config's path is absolute (resolve_config_path makes it
996
1217
  # so), to show which of the defaults was picked up.
997
1218
  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)}"
1219
+ puts "Working Dir: #{Dir.pwd}"
1220
+ puts(argv[1] ? "Config: #{relative_path(config_path)}" : "Config: [default] #{config_path}")
1221
+ puts "Prompt: #{relative_path(prompt_path)}"
1222
+ puts "Run Dir: #{relative_path(run_dir)}"
1001
1223
  puts "\nReview Agents (#{agents.size}):"
1002
1224
  agents.each_with_index do |agent, i|
1003
1225
  puts " ##{i + 1} #{agent_descriptor(agent)}"
@@ -1009,38 +1231,42 @@ module AgentCouncil
1009
1231
  agents.each_with_index do |agent, i|
1010
1232
  index = i + 1
1011
1233
  pool.start do
1012
- provider = agent.is_a?(Hash) ? agent['provider'] : nil
1013
- model = agent.is_a?(Hash) ? agent['model'] : nil
1014
1234
  meta = report_meta.merge('agent_index' => index)
1015
- (label, ok, detail, usage), elapsed = timed do
1235
+ (label, ok, detail, usage, warnings), elapsed = timed do
1016
1236
  run_agent(agent, analyst_prompt, reviews_dir, file_prefix,
1017
1237
  index: index,
1018
1238
  meta: meta,
1019
- header: ->(run_fields) { byline_table(meta.merge(run_fields), provider, model) },
1239
+ header: ->(run_fields) { byline_table(meta.merge(run_fields), agent) },
1020
1240
  pool: pool)
1021
1241
  end
1022
- [label, ok, detail, elapsed, usage]
1242
+ [label, ok, detail, elapsed, usage, warnings]
1023
1243
  end
1024
1244
  end
1025
- results = pool.collect do |label, ok, detail, elapsed|
1245
+ # Printed here, in the main thread, as everything is (see WorkerPool).
1246
+ results = pool.collect do |label, ok, detail, elapsed, _usage, warnings|
1026
1247
  duration = format_duration(elapsed)
1027
1248
  puts(ok ? " ✓ #{duration} #{label}" : " ✗ #{duration} #{label}\n #{detail}")
1249
+ puts warning_lines(warnings)
1028
1250
  end
1029
1251
 
1030
1252
  failed = results.count { |_, ok, _| !ok }
1031
1253
  puts "\nReviews (in #{relative_path(reviews_dir)}):"
1032
1254
  puts format_result_table(results)
1033
1255
  puts "\n--- Reviews complete (#{results.size - failed}/#{results.size} succeeded" \
1034
- "#{usage_summary(results.map(&:last))}) ---"
1256
+ "#{usage_summary(results.map { |_, _, _, _, usage| usage })}) ---"
1035
1257
  # 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)
1258
+ analyst_runs = agents.zip(results).each_with_index.map do |(agent, result), i|
1259
+ _, ok, detail, elapsed, usage, warnings = result
1260
+ run_entry(agent, ok, detail, elapsed, usage, index: i + 1, dir: REVIEWS_DIR_NAME, warnings: warnings)
1038
1261
  end
1039
1262
  write_run_file(run_dir, analyst_runs, [])
1040
1263
 
1041
1264
  if consolidator
1042
1265
  puts "\nConsolidation Report (in #{relative_path(run_dir)}):"
1043
- failures = results.reject { |_, ok, _| ok }.map { |label, _, detail, _| [label, detail] }
1266
+ failures = agents.zip(results).reject { |_, (_, ok)| ok }.map do |agent, result|
1267
+ label, _, detail, _, _, warnings = result
1268
+ [label, failure_with_warnings(detail, warnings), Harnesses.name_of(agent)]
1269
+ end
1044
1270
  pool.start do
1045
1271
  timed do
1046
1272
  run_consolidation(consolidator, prompt, run_dir, file_prefix,
@@ -1048,9 +1274,10 @@ module AgentCouncil
1048
1274
  pool: pool)
1049
1275
  end
1050
1276
  end
1051
- (label, ok, detail, usage, meta_name), elapsed = pool.collect.first
1277
+ (label, ok, detail, usage, meta_name, warnings), elapsed = pool.collect.first
1052
1278
  puts format_result_table([[label, ok, detail, elapsed, usage]])
1053
- entry = run_entry(consolidator, ok, detail, elapsed, usage, meta_report: meta_name)
1279
+ puts warning_lines(warnings)
1280
+ entry = run_entry(consolidator, ok, detail, elapsed, usage, meta_report: meta_name, warnings: warnings)
1054
1281
  write_run_file(run_dir, analyst_runs, [entry])
1055
1282
  puts_consolidation_status(ok)
1056
1283
  end
@@ -1097,20 +1324,20 @@ module AgentCouncil
1097
1324
  end
1098
1325
  consolidator = config['consolidator'] if config.is_a?(Hash)
1099
1326
  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
1327
+ abort_on_entry_errors({ "'consolidator'" => consolidator }, config_path,
1328
+ hint: "If this run predates the 'harness' key, its consolidator ran under pi: " \
1329
+ "add 'harness: pi' to the copy.")
1103
1330
  unless File.file?(CONSOLIDATE_PROMPT_PATH)
1104
1331
  abort "Consolidation template missing: #{CONSOLIDATE_PROMPT_PATH}"
1105
1332
  end
1106
1333
 
1107
1334
  file_prefix = "#{fields['run_stamp']}_#{fields['query']}" # as in a normal run
1108
- filename = consolidated_filename(file_prefix, consolidator['provider'], consolidator['model'])
1335
+ filename = consolidated_filename(file_prefix, consolidator)
1109
1336
  unless bare_name?(filename)
1110
1337
  abort "Invalid run_stamp or query in #{reviews_dir}: #{fields.values_at('run_stamp', 'query').inspect}"
1111
1338
  end
1112
1339
  names = [nil, 'findings', 'meta'].map do |part|
1113
- consolidated_filename(file_prefix, consolidator['provider'], consolidator['model'], part)
1340
+ consolidated_filename(file_prefix, consolidator, part)
1114
1341
  end
1115
1342
  existing = names.select { |name| File.exist?(File.join(run_dir, name)) }
1116
1343
  unless existing.empty?
@@ -1122,21 +1349,22 @@ module AgentCouncil
1122
1349
  prompt = File.read(prompt_path, encoding: ENCODING)
1123
1350
  abort "Prompt copy is empty: #{prompt_path}" if prompt.empty?
1124
1351
 
1125
- abort_unless_harness_installed
1352
+ abort_unless_harnesses_installed([consolidator])
1126
1353
 
1127
1354
  # In the same key order as a normal run's front matter.
1128
1355
  meta = fields.slice('role', 'timestamp', 'query', 'prompt_file', 'config_file', 'config_source',
1129
1356
  'run_stamp')
1130
1357
  meta['timestamp'] = iso_timestamp(meta['timestamp']) if meta['timestamp'].is_a?(Time)
1131
1358
 
1132
- puts "Config: #{relative_path(config_path)}"
1133
- puts "Prompt: #{relative_path(prompt_path)}"
1134
- puts "Run Dir: #{relative_path(run_dir)}"
1359
+ puts "Working Dir: #{Dir.pwd}"
1360
+ puts "Config: #{relative_path(config_path)}"
1361
+ puts "Prompt: #{relative_path(prompt_path)}"
1362
+ puts "Run Dir: #{relative_path(run_dir)}"
1135
1363
  puts "\nConsolidator Agent:\n #{agent_descriptor(consolidator)}"
1136
1364
  puts "\nConsolidation Report (in #{relative_path(run_dir)}, " \
1137
1365
  "from #{reports.size} review#{'s' unless reports.size == 1}):"
1138
- failures = missing_agents(config, reports)
1139
1366
  analysts, consolidations = read_run_file(run_dir)
1367
+ failures = missing_agents(config, reports, analysts)
1140
1368
  pool = WorkerPool.new(grace: INTERRUPT_GRACE_SECONDS)
1141
1369
  pool.trap_signals
1142
1370
  pool.start do
@@ -1146,16 +1374,18 @@ module AgentCouncil
1146
1374
  analyst_runs: analysts || [], pool: pool)
1147
1375
  end
1148
1376
  end
1149
- (label, ok, detail, usage, meta_name), elapsed = pool.collect.first
1377
+ (label, ok, detail, usage, meta_name, warnings), elapsed = pool.collect.first
1150
1378
  puts format_result_table([[label, ok, detail, elapsed, usage]])
1379
+ puts warning_lines(warnings)
1151
1380
  # Added to the run's run.json. Without one (deleted, or unreadable),
1152
1381
  # none is written: a total covering only this consolidation would
1153
1382
  # pass for the run's.
1154
1383
  if analysts
1155
- entry = run_entry(consolidator, ok, detail, elapsed, usage, meta_report: meta_name)
1384
+ entry = run_entry(consolidator, ok, detail, elapsed, usage, meta_report: meta_name, warnings: warnings)
1156
1385
  write_run_file(run_dir, analysts, consolidations + [entry])
1157
1386
  else
1158
- warn "No readable #{RUN_FILENAME} in #{relative_path(run_dir)}; not recording this consolidation's run"
1387
+ warn "No readable #{RUN_FILENAME} in #{relative_path(run_dir)}, " \
1388
+ "so this consolidation won't be recorded in one"
1159
1389
  end
1160
1390
  puts_consolidation_status(ok)
1161
1391
  exit(ok ? 0 : 1)
@@ -1173,30 +1403,62 @@ module AgentCouncil
1173
1403
  File.basename(name) == name
1174
1404
  end
1175
1405
 
1176
- # What --consolidate tells the consolidator about an agent without a report.
1406
+ # A failed agent's reason as the consolidator is told it: its error, then
1407
+ # any warnings about the agent, since they may be why it failed.
1408
+ module_function def failure_with_warnings(detail, warnings)
1409
+ [detail, *Array(warnings).map { |warning| "warning: #{warning}" }].join('; ')
1410
+ end
1411
+
1412
+ # What --consolidate tells the consolidator about an agent without a
1413
+ # report when run.json doesn't record that it failed.
1177
1414
  MISSING_REPORT_REASON =
1178
1415
  'reason not recorded (it may have failed, been interrupted, or had its report removed)'
1179
1416
 
1180
1417
  # 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)
1418
+ # [label, reason, harness] triples, as a run tells its consolidator. The
1419
+ # reason is the error and warnings run.json records for the agent's
1420
+ # failure (analyst_runs: its analyst entries); else it isn't known,
1421
+ # and needn't be a failure: the run may have been interrupted, or a
1422
+ # report removed. An agent the config copy gives an unknown harness is
1423
+ # still listed: it needs no harness to be labeled, and the config may
1424
+ # come from a newer version.
1425
+ module_function def missing_agents(config, reports, analyst_runs = [])
1184
1426
  agents = config['agents'].is_a?(Array) ? config['agents'] : []
1185
1427
  present = reports.map(&:first)
1186
1428
  agents.each_with_index.filter_map do |agent, i|
1187
- next unless valid_agent_entry?(agent)
1429
+ next unless labelable_entry?(agent)
1188
1430
 
1189
1431
  label = agent_label(agent['provider'], agent['model'], i + 1)
1190
- [label, MISSING_REPORT_REASON] unless present.include?(label)
1432
+ next if present.include?(label)
1433
+
1434
+ [label, recorded_failure(agent, i + 1, analyst_runs) || MISSING_REPORT_REASON, Harnesses.name_of(agent)]
1191
1435
  end
1192
1436
  end
1193
1437
 
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)
1438
+ # The reason run.json records for the failure of agent (the config
1439
+ # entry at 1-based index), with its warnings, or nil if none is recorded.
1440
+ module_function def recorded_failure(agent, index, analyst_runs)
1441
+ run = Array(analyst_runs).find do |entry|
1442
+ entry.is_a?(Hash) && entry['agent_index'] == index && entry['ok'] == false &&
1443
+ entry.values_at('provider', 'model') == agent.values_at('provider', 'model') &&
1444
+ Harnesses.name_of(entry) == Harnesses.name_of(agent)
1445
+ end
1446
+ return nil unless run && run['error'].is_a?(String)
1447
+
1448
+ failure_with_warnings(run['error'], Array(run['warnings']).grep(String))
1449
+ end
1450
+
1451
+ # Checked up front, before any run dir is created or model called: the
1452
+ # executable of every harness the config entries use (validated ones, so
1453
+ # each harness is known).
1454
+ module_function def abort_unless_harnesses_installed(entries)
1455
+ names = entries.map { |entry| Harnesses.module_for(entry)::NAME }.uniq
1456
+ missing = names.reject { |name| executable_on_path?(name) }
1457
+ return if missing.empty?
1197
1458
 
1459
+ lines = missing.map { |name| "#{name} executable not found; is `#{name}` installed and on your PATH?" }
1198
1460
  abort <<~MESSAGE
1199
- #{HARNESS::NAME} executable not found; is `#{HARNESS::NAME}` installed and on your PATH?
1461
+ #{lines.join("\n")}
1200
1462
  See "Prerequisites" in #{File.join(PROJECT_ROOT, 'README.md')}
1201
1463
  MESSAGE
1202
1464
  end