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.
@@ -21,16 +21,9 @@ cost to fix, and give a high-level strategy for addressing it.
21
21
  Do not run anything that deploys, publishes, migrates real data, or calls paid or production services.
22
22
  - Follow the Project-Specific Instructions at the end, if any; they override these general rules where they
23
23
  conflict.
24
- - If earlier reports of this kind exist in the output directory, compare with the most recent one and note
25
- what has improved or regressed.
26
24
 
27
25
  ## Output
28
26
 
29
- Write the report to `untracked/` (create it if needed) unless the Project-Specific Instructions name another
30
- directory. Name it `YYYY-MM-DD-HH-MM-SS-state-of-the-code-base-<agent>.md`, where the timestamp is the current
31
- UTC time to the second and `<agent>` is your lowercase tool or model family name (e.g. `claude`, `codex`,
32
- `gemini`, `zai`).
33
-
34
27
  Begin the report with:
35
28
 
36
29
  1. The most recent git commit (hash and subject) at the time you begin.
@@ -18,8 +18,8 @@ several agents run it concurrently against the same coverage data.
18
18
 
19
19
  This prompt never asks the user anything, so it runs the same interactively or
20
20
  headless. Never stop to wait for input: when a precondition fails, stop with an
21
- error message instead. The invocation may name a different report location
22
- (e.g. "write the report to `tmp/reports`") or coverage file location.
21
+ error message instead. The invocation may name a different coverage file
22
+ location.
23
23
 
24
24
  ### Preconditions
25
25
 
@@ -47,16 +47,16 @@ Before you begin the analysis:
47
47
  - Get every coverage number from cov-loupe. Do not read `coverage.json`
48
48
  directly, and do not estimate coverage by reading tests. Aggregating
49
49
  cov-loupe's per-line output into area totals is expected (see Step 4).
50
- - Prefer the cov-loupe MCP server. If it is unavailable, use the CLI
51
- (`cov-loupe`, or `bundle exec cov-loupe` if it is in the Gemfile; run
52
- `cov-loupe --help` for usage), adding `-m cli -fJ` for JSON output. Say in
53
- the report which one you used.
50
+ - Use the cov-loupe CLI (`cov-loupe`, or `bundle exec cov-loupe` if it is in
51
+ the Gemfile; run `cov-loupe --help` for usage), adding `-m cli -fJ` for JSON
52
+ output.
54
53
  - Use source and test files only to define the logical areas and to judge the
55
54
  importance of uncovered code.
56
55
  - Do not run the test suite, and do not modify source files, test files, or
57
56
  coverage output. Other agents may be running this analysis concurrently
58
- against the same data. This is a read-only analysis; the only file you
59
- write is the report.
57
+ against the same data. This is a read-only analysis: write no
58
+ files except in a temporary directory of your own outside the
59
+ project (see Step 4).
60
60
  - Before recommending tests for uncovered code, check whether it is
61
61
  intentionally excluded or untested: SimpleCov filters and `# :nocov:`
62
62
  markers, and any project documentation or code comments explaining why.
@@ -66,7 +66,8 @@ Before you begin the analysis:
66
66
  The user must run the full, passing test suite before this analysis. Verify
67
67
  what you can, and if any check below fails, stop with an error that names the
68
68
  failed check, gives the coverage file's path, size, and modification time (if
69
- it exists), and tells the user to rerun the full suite. Do not write a report.
69
+ it exists), and tells the user to rerun the full suite. Give only that
70
+ error, not a report.
70
71
 
71
72
  1. Find the SimpleCov configuration (`.simplecov`, `spec/spec_helper.rb`,
72
73
  `test/test_helper.rb`, or wherever the project starts SimpleCov) and the
@@ -76,10 +77,9 @@ it exists), and tells the user to rerun the full suite. Do not write a report.
76
77
  UTC) from the file system (e.g. `ls -l` or `stat`); this metadata is not
77
78
  coverage data, so reading it is allowed.
78
79
  2. Run the project totals with the tracked globs from Step 2
79
- (`project_coverage_totals` / `cov-loupe -m cli -fJ -g '<globs>' totals`)
80
- and the file list with the same globs (`project_coverage` /
81
- `cov-loupe -m cli -fJ -g '<globs>' list`). `timestamp_status` must be `ok`,
82
- and `newer_files`, `deleted_files`, `length_mismatch_files`,
80
+ (`cov-loupe -m cli -fJ -g '<globs>' totals`) and the file list with the
81
+ same globs (`cov-loupe -m cli -fJ -g '<globs>' list`). `timestamp_status`
82
+ must be `ok`, and `newer_files`, `deleted_files`, `length_mismatch_files`,
83
83
  `unreadable_files`, and `skipped_files` must all be empty. These show
84
84
  whether source files changed after the run.
85
85
  3. No test, fixture, or configuration file may be newer than the coverage
@@ -102,7 +102,7 @@ staleness failure; it is a finding for Step 2.
102
102
  1. Get overall totals with no globs, then with tracked globs matching the
103
103
  code SimpleCov is meant to measure (from its `track_files` and filter
104
104
  settings; typically `lib/**/*.rb`, or `app/**/*.rb,lib/**/*.rb` for Rails).
105
- Passing `tracked_globs` makes cov-loupe report tracked files that have
105
+ Passing tracked globs (`-g`) makes cov-loupe report tracked files that have
106
106
  **no** coverage data at all (`missing_tracked_files`, `without_coverage`);
107
107
  these are files never loaded by the suite and are often the biggest real
108
108
  gap.
@@ -161,16 +161,15 @@ and more tokens than a file-level rollup; that is the point.
161
161
  ## Step 4: Compute coverage per area
162
162
 
163
163
  1. For each file touched by an area, get per-line data with
164
- `file_coverage_detailed` / `cov-loupe -m cli -fJ detailed <path>`. Each row
165
- gives a line number, its hit count, and whether it is covered; lines that
166
- are not coverable (comments, blank lines, `end`) do not appear.
164
+ `cov-loupe -m cli -fJ detailed <path>`. Each row gives a line number, its
165
+ hit count, and whether it is covered; lines that are not coverable
166
+ (comments, blank lines, `end`) do not appear.
167
167
  2. For each area, sum the covered and coverable lines that fall in its line
168
168
  ranges, and compute the percentage. Also record the number of code units
169
169
  in the area and its weakest units (e.g. the least-covered methods).
170
170
  3. Get a broader area's numbers by summing its children's line counts, never
171
171
  by averaging child percentages.
172
172
  4. For an area made of whole files, cross-check your sums against
173
- `project_coverage_totals` with `tracked_globs` /
174
173
  `cov-loupe -m cli -fJ -g '<globs>' totals`; they must match exactly.
175
174
  5. Confirm that the line totals for the partition level from Step 3 add up to
176
175
  the project's covered and total lines for the same overall globs. If they
@@ -192,8 +191,8 @@ report.
192
191
 
193
192
  For each selected file or area:
194
193
 
195
- 1. Get the uncovered lines (`file_uncovered_lines` /
196
- `cov-loupe -m cli -fJ uncovered <path>`); use `file_coverage_detailed` or
194
+ 1. Get the uncovered lines (`cov-loupe -m cli -fJ uncovered <path>`); use
195
+ `cov-loupe -m cli -fJ detailed <path>` or
197
196
  `cov-loupe -m cli -s uncovered -n 2 uncovered <path>` to see the source in
198
197
  context.
199
198
  2. Characterize each cluster of uncovered lines: error/rescue path, edge-case
@@ -242,24 +241,12 @@ Keep this qualitative and evidence-based; cite test files and line numbers.
242
241
 
243
242
  ## Report
244
243
 
245
- Write your analysis in the project root (or in the directory the invocation
246
- names) as a Markdown file whose name is:
247
- - today's date in UTC `%Y-%m-%d-%H-%M` format +
248
- - '-test-coverage-analysis-' +
249
- - your name (e.g. 'codex', 'claude', 'gemini') +
250
- - the `.md` extension.
251
-
252
- If a file with that name already exists (another agent finished in the same
253
- minute), append `-2`, `-3`, and so on before the extension. Never overwrite an
254
- existing report.
255
-
256
- The file should have the following structure:
244
+ The report should have the following structure:
257
245
 
258
246
  ---
259
247
 
260
248
  ### Executive Summary
261
- - Commit cited, cov-loupe interface used (MCP or CLI), and the results of the
262
- Step 1 checks.
249
+ - Commit cited and the results of the Step 1 checks.
263
250
  - The coverage file's path (relative to the project root), size, and
264
251
  modification time (UTC), so readers can tell which test run the report
265
252
  describes.
@@ -335,12 +322,12 @@ table, give each task a ready-to-use prompt the user can give an AI assistant
335
322
  to implement it, keyed by its number.
336
323
 
337
324
  ### Appendix: Commands Run
338
- Every cov-loupe call (MCP tool name and arguments, or CLI command) and
325
+ Every cov-loupe command and
339
326
  freshness check used to produce the numbers, plus any aggregation script, so the
340
327
  report can be reproduced.
341
328
 
342
329
  ---
343
330
 
344
- End your final message with the report's path and the one-line verdict, or,
345
- if you stopped early, with the error. A headless caller can then find the
331
+ End the report by repeating the one-line verdict, or, if you stopped early,
332
+ give only the error. A headless caller can then find the
346
333
  outcome without parsing the rest of your output.
data/exe/agent-council CHANGED
@@ -3,7 +3,13 @@
3
3
 
4
4
  # agent-council — executable entry point. All code lives in lib/:
5
5
  # lib/agent_council.rb orchestration (AgentCouncil)
6
+ # lib/agent_council/harnesses.rb harnesses by name (AgentCouncil::Harnesses)
7
+ # lib/agent_council/harnesses/scaffold.rb read-only scaffolding every harness appends
6
8
  # lib/agent_council/harnesses/pi_harness.rb pi-specific behavior (AgentCouncil::Harnesses::PiHarness)
9
+ # lib/agent_council/harnesses/claude_code_harness.rb
10
+ # Claude Code-specific behavior (ClaudeCodeHarness)
11
+ # lib/agent_council/harnesses/codex_harness.rb
12
+ # Codex-specific behavior (CodexHarness)
7
13
  #
8
14
  # Usage, options, and AGENT_COUNCIL_OPTS: agent-council -h, and the README.
9
15
 
@@ -0,0 +1,204 @@
1
+ # frozen_string_literal: true
2
+
3
+ # AgentCouncil::Harnesses::ClaudeCodeHarness — all knowledge specific to
4
+ # the Claude Code harness: how to invoke the claude CLI for one agent,
5
+ # with its tool allowlist and the shared read-only scaffolding, and how to
6
+ # read its stream-json output afterward.
7
+ #
8
+ # AgentCouncil is harness-agnostic and finds this module through
9
+ # AgentCouncil::Harnesses (lib/agent_council/harnesses.rb), by its NAME.
10
+ # Authentication and billing are left to Claude Code: an agent bills however
11
+ # claude would at the user's terminal.
12
+
13
+ require 'json'
14
+ require_relative 'scaffold'
15
+
16
+ module AgentCouncil
17
+ module Harnesses
18
+ module ClaudeCodeHarness
19
+ NAME = 'claude'
20
+
21
+ # Analysis toolset (Claude Code's built-in tool names): Edit, Write, and
22
+ # the rest are absent. Bash, a full shell, stays for investigation;
23
+ # only the scaffolding text asks the model to use it read-only.
24
+ TOOLS = 'Read,Grep,Glob,Bash'
25
+
26
+ # Invocation for one agent. The substantive prompt is not part of
27
+ # argv; it is piped to stdin. provider is not passed: Claude Code
28
+ # takes none, so an entry's provider only labels the agent (e.g.
29
+ # bedrock, for a claude set up to use it).
30
+ module_function def argv(_provider, model)
31
+ [
32
+ NAME,
33
+ '-p', # non-interactive: process prompt and exit
34
+ '--output-format', 'stream-json', # JSONL event stream on stdout
35
+ '--verbose', # required by stream-json with -p
36
+ '--no-session-persistence', # ephemeral: no session saved
37
+ '--tools', TOOLS, # the only built-in tools available
38
+ '--allowedTools', TOOLS, # ...and pre-approved, since -p can't ask
39
+ '--permission-mode', 'manual', # the same for every user, whatever their defaultMode
40
+ '--model', model,
41
+ '--append-system-prompt', Harnesses.scaffold_text
42
+ ]
43
+ end
44
+
45
+ # --- event stream reading ---
46
+
47
+ # The events of a stream-json stream, in order. Unparseable lines and
48
+ # non-objects are skipped.
49
+ module_function def events(jsonl)
50
+ jsonl.each_line.filter_map do |line|
51
+ event =
52
+ begin
53
+ JSON.parse(line)
54
+ rescue JSON::ParserError
55
+ nil
56
+ end
57
+ event if event.is_a?(Hash)
58
+ end
59
+ end
60
+
61
+ # The agent's result event: the last one, which ends the stream. nil if
62
+ # there is none, e.g. for an agent that was killed.
63
+ module_function def result_event(jsonl)
64
+ events(jsonl).reverse_each.detect { |event| event['type'] == 'result' }
65
+ end
66
+
67
+ # The messages of the stream's assistant events, in order (several per
68
+ # model request, one per content block).
69
+ module_function def assistant_messages(jsonl)
70
+ events(jsonl).filter_map do |event|
71
+ message = event['message'] if event['type'] == 'assistant'
72
+ message if message.is_a?(Hash)
73
+ end
74
+ end
75
+
76
+ # The final response: the result event's text, for an agent that didn't
77
+ # fail.
78
+ module_function def final_response(jsonl)
79
+ result = result_event(jsonl)
80
+ return nil unless result && result['is_error'] != true
81
+
82
+ text = result['result']
83
+ text.is_a?(String) ? text : nil
84
+ end
85
+
86
+ # Our usage keys, each mapped to Claude Code's name for it. Its input
87
+ # excludes cache reads and writes, as pi's does.
88
+ USAGE_KEYS = { 'input' => 'input_tokens', 'output' => 'output_tokens',
89
+ 'cache_read' => 'cache_read_input_tokens',
90
+ 'cache_write' => 'cache_creation_input_tokens' }.freeze
91
+
92
+ # Token usage as AgentCouncil expects it (see Harnesses), from the
93
+ # result event alone: it totals all the agent's requests, while the assistant
94
+ # events' usage is per-message snapshots that undercount output. nil
95
+ # when the stream has no result event (as for an agent whose claude was
96
+ # killed: no usage beats an undercount) or reports no usage (as when
97
+ # the agent never reached a model).
98
+ module_function def usage(jsonl)
99
+ result = result_event(jsonl)
100
+ usage = result && result['usage']
101
+ return nil unless usage.is_a?(Hash)
102
+
103
+ totals = USAGE_KEYS.transform_values { |key| count(usage[key]) }
104
+ return nil if totals.values.all?(&:zero?)
105
+
106
+ cost = count(result['total_cost_usd'])
107
+ cost.positive? ? totals.merge('cost' => cost.round(6)) : totals
108
+ end
109
+
110
+ module_function def count(value)
111
+ value.is_a?(Numeric) && value.positive? ? value : 0
112
+ end
113
+
114
+ # Why the agent produced no usable report, or nil. A failed agent has a
115
+ # result event with is_error true (its subtype is usually still
116
+ # "success", so it isn't checked); one that isn't flagged but has no
117
+ # text is reported as such, since the report is that text. The reason
118
+ # is its errors, if any (e.g. the turn limit, with no result text),
119
+ # otherwise its result text (e.g. "Not logged in · Please run
120
+ # /login").
121
+ module_function def error_message(jsonl)
122
+ result = result_event(jsonl)
123
+ return 'the stream has no result event' unless result
124
+ return error_reason(result) || 'the agent failed and gave no reason' if result['is_error'] == true
125
+
126
+ text = result['result']
127
+ 'the result event has no text' unless text.is_a?(String) && !text.strip.empty?
128
+ end
129
+
130
+ # The reason a failed agent's result event gives, or nil if it gives none.
131
+ module_function def error_reason(result)
132
+ errors = Array(result['errors']).grep(String).map(&:strip).reject(&:empty?)
133
+ return errors.join('; ') unless errors.empty?
134
+
135
+ text = result['result']
136
+ text if text.is_a?(String) && !text.strip.empty?
137
+ end
138
+
139
+ # Why an agent that exited nonzero failed. Claude Code explains a failure
140
+ # in a result event with is_error true, and its stderr is then
141
+ # usually empty, so that reason, if it gives one, comes first.
142
+ # Otherwise stderr is likelier to say why (e.g. for a crash) than
143
+ # whatever else the stream shows (e.g. a result with no text), which
144
+ # is the last resort. Returned whole: the caller puts it on one line
145
+ # and shortens it (see Harnesses).
146
+ module_function def exit_detail(stdout, stderr)
147
+ result = result_event(stdout)
148
+ reason = error_reason(result) if result && result['is_error'] == true
149
+ return reason if reason
150
+
151
+ stderr_line = stderr.lines.map(&:strip).reject(&:empty?).first
152
+ return stderr_line if stderr_line
153
+
154
+ (error_message(stdout) if result) || 'no error output'
155
+ end
156
+
157
+ # Warnings about an agent, succeeded or not: the tool calls Claude Code
158
+ # refused, which -p mode can't ask about. The agent usually still
159
+ # succeeds (the model saw the refusal and answered without that
160
+ # call), but its report may be missing what the call would have
161
+ # found; an agent that fails (say, out of turns) may have failed
162
+ # because of them.
163
+ module_function def warnings(jsonl)
164
+ result = result_event(jsonl)
165
+ denials = result && result['permission_denials']
166
+ return [] unless denials.is_a?(Array) && !denials.empty?
167
+
168
+ calls = denials.map { |denial| denied_call(denial) }.uniq
169
+ listed = calls.first(MAX_LISTED_CALLS).map do |tool, target|
170
+ target ? "#{tool} (#{shorten(target)})" : tool
171
+ end
172
+ listed << "and #{calls.size - listed.size} more" if calls.size > listed.size
173
+ ["Claude Code refused #{denials.size} tool call#{'s' unless denials.size == 1}: #{listed.join('; ')}"]
174
+ end
175
+
176
+ # Distinct refused calls named in a warning, so an agent refused many
177
+ # times still gets a warning of a readable length.
178
+ MAX_LISTED_CALLS = 5
179
+
180
+ # The tool_input keys that say what a refused call was for, in order
181
+ # of preference: Bash's command, Read's file_path, then Grep's and
182
+ # Glob's pattern and path.
183
+ TARGET_KEYS = %w[command file_path pattern path].freeze
184
+
185
+ # A refused tool call as [tool, target]: its tool and what it was for,
186
+ # such as a Bash command or the file a Read asked for, on one line,
187
+ # or nil if the call gives none. Compared whole, so calls that differ
188
+ # only past where a warning shortens them still count as different.
189
+ module_function def denied_call(denial)
190
+ return ['unknown tool', nil] unless denial.is_a?(Hash)
191
+
192
+ tool = denial['tool_name'].is_a?(String) ? denial['tool_name'] : 'unknown tool'
193
+ input = denial['tool_input']
194
+ target = TARGET_KEYS.map { |key| input[key] }.grep(String).first if input.is_a?(Hash)
195
+ target = target&.gsub(/\s+/, ' ')&.strip
196
+ [tool, (target unless target.nil? || target.empty?)]
197
+ end
198
+
199
+ module_function def shorten(target)
200
+ target.length > 80 ? "#{target[0, 80]}..." : target
201
+ end
202
+ end
203
+ end
204
+ end
@@ -0,0 +1,221 @@
1
+ # frozen_string_literal: true
2
+
3
+ # AgentCouncil::Harnesses::CodexHarness — all knowledge specific to the
4
+ # OpenAI Codex CLI harness: how to invoke `codex exec` for one agent,
5
+ # with the shared scaffolding, and how to read
6
+ # its --json event stream afterward.
7
+ #
8
+ # AgentCouncil is harness-agnostic and finds this module through
9
+ # AgentCouncil::Harnesses (lib/agent_council/harnesses.rb), by its NAME.
10
+ # Authentication and billing are left to Codex: an agent bills however
11
+ # codex would at the user's terminal (ChatGPT plan or API key).
12
+
13
+ require 'json'
14
+ require_relative 'scaffold'
15
+
16
+ module AgentCouncil
17
+ module Harnesses
18
+ module CodexHarness
19
+ NAME = 'codex'
20
+
21
+ # Invocation for one agent. The substantive prompt is not part of
22
+ # argv; it is piped to stdin ('-'). provider is not passed: like
23
+ # Claude Code's, an entry's provider only labels the agent, and Codex
24
+ # uses the model_provider its own config names.
25
+ #
26
+ # No --sandbox or approval flags: the user's sandbox_mode applies, as
27
+ # in an interactive session, along with the rest of their config.toml
28
+ # (MCP servers and plugins included) and the repository's AGENTS.md.
29
+ # Their approval_policy doesn't: codex exec never asks, so a command
30
+ # that needs approval is refused. Under workspace-write,
31
+ # Codex lets commands write $TMPDIR, which the scaffolding sends
32
+ # agents to; under read-only nothing is writable.
33
+ #
34
+ # developer_instructions replaces any the user's config sets; Codex
35
+ # has no way to append to it.
36
+ module_function def argv(_provider, model)
37
+ [
38
+ NAME, 'exec',
39
+ '--json', # JSONL event stream on stdout
40
+ '--ephemeral', # no session files saved; subagents then fail to spawn
41
+ '--skip-git-repo-check', # run anywhere, as pi and claude agents do
42
+ '--color', 'never',
43
+ '--model', model,
44
+ '-c', "developer_instructions=#{toml_string(Harnesses.scaffold_text)}",
45
+ '-' # read the prompt from stdin
46
+ ]
47
+ end
48
+
49
+ # A TOML basic string (JSON's string escapes are valid TOML ones), so
50
+ # -c reads the value as the string itself, not as TOML to parse.
51
+ module_function def toml_string(text)
52
+ JSON.generate(text)
53
+ end
54
+
55
+ # --- event stream reading ---
56
+
57
+ # The events of a --json stream, in order. Unparseable lines and
58
+ # non-objects are skipped.
59
+ module_function def events(jsonl)
60
+ jsonl.each_line.filter_map do |line|
61
+ event =
62
+ begin
63
+ JSON.parse(line)
64
+ rescue JSON::ParserError
65
+ nil
66
+ end
67
+ event if event.is_a?(Hash)
68
+ end
69
+ end
70
+
71
+ # The completed items of the given type, in order.
72
+ module_function def completed_items(jsonl, type)
73
+ events(jsonl).filter_map do |event|
74
+ item = event['item'] if event['type'] == 'item.completed'
75
+ item if item.is_a?(Hash) && item['type'] == type
76
+ end
77
+ end
78
+
79
+ # The agent's messages (its text between and after tool calls), in order.
80
+ module_function def assistant_messages(jsonl)
81
+ completed_items(jsonl, 'agent_message')
82
+ end
83
+
84
+ # The event that ended the agent's turn: turn.completed or
85
+ # turn.failed. nil if there is none, e.g. for an agent that was killed.
86
+ module_function def turn_end(jsonl)
87
+ events(jsonl).reverse_each.detect { |event| %w[turn.completed turn.failed].include?(event['type']) }
88
+ end
89
+
90
+ # The final response: the last agent message with text, for an agent
91
+ # whose turn completed. Earlier messages narrate its tool use.
92
+ module_function def final_response(jsonl)
93
+ return nil unless turn_end(jsonl)&.fetch('type') == 'turn.completed'
94
+
95
+ message = assistant_messages(jsonl).reverse_each.detect { |m| text_of(m) }
96
+ message && text_of(message)
97
+ end
98
+
99
+ # A message's text, or nil if it has none.
100
+ module_function def text_of(item)
101
+ text = item['text']
102
+ text if text.is_a?(String) && !text.strip.empty?
103
+ end
104
+
105
+ # Token usage as AgentCouncil expects it (see Harnesses), from the
106
+ # turn.completed event, which totals the turn's requests. Codex's
107
+ # input_tokens is all input, OpenAI's convention, so the cached reads
108
+ # and writes it reports are subtracted from it; reasoning tokens are
109
+ # part of output_tokens. Codex prices nothing, so there is no 'cost'.
110
+ # nil when the turn didn't complete or reports no usage.
111
+ module_function def usage(jsonl)
112
+ turn = turn_end(jsonl)
113
+ usage = turn['usage'] if turn && turn['type'] == 'turn.completed'
114
+ return nil unless usage.is_a?(Hash)
115
+
116
+ cache_read = count(usage['cached_input_tokens'])
117
+ cache_write = count(usage['cache_write_input_tokens'])
118
+ totals = { 'input' => [count(usage['input_tokens']) - cache_read - cache_write, 0].max,
119
+ 'output' => count(usage['output_tokens']),
120
+ 'cache_read' => cache_read,
121
+ 'cache_write' => cache_write }
122
+ totals.values.all?(&:zero?) ? nil : totals
123
+ end
124
+
125
+ module_function def count(value)
126
+ value.is_a?(Numeric) && value.positive? ? value : 0
127
+ end
128
+
129
+ # Why the agent produced no usable report, or nil. A failed turn ends
130
+ # with turn.failed, whose error says why (e.g. a model the account
131
+ # can't use); a completed one with no text is reported as such.
132
+ module_function def error_message(jsonl)
133
+ turn = turn_end(jsonl)
134
+ return 'the stream has no turn.completed or turn.failed event' unless turn
135
+ return failure_reason(jsonl) || 'the turn failed and gave no reason' if turn['type'] == 'turn.failed'
136
+
137
+ 'the agent gave no final message' unless final_response(jsonl)
138
+ end
139
+
140
+ # The reason a failed turn gives: its turn.failed error message, else
141
+ # the last top-level error event's. nil if neither gives one.
142
+ module_function def failure_reason(jsonl)
143
+ all = events(jsonl)
144
+ failed = all.reverse_each.detect { |event| event['type'] == 'turn.failed' }
145
+ error = failed['error'] if failed
146
+ reason = error['message'] if error.is_a?(Hash)
147
+ return reason.strip if reason.is_a?(String) && !reason.strip.empty?
148
+
149
+ nonblank(all.filter_map { |event| event['message'] if event['type'] == 'error' }).last
150
+ end
151
+
152
+ # Why an agent that exited nonzero failed. Codex explains a failed
153
+ # turn in the stream, with stderr usually empty, so that comes first;
154
+ # then stderr (e.g. for a bad flag or a crash).
155
+ module_function def exit_detail(stdout, stderr)
156
+ reason = failure_reason(stdout)
157
+ return reason if reason
158
+
159
+ stderr.lines.map(&:strip).reject(&:empty?).first || 'no error output'
160
+ end
161
+
162
+ # Warnings about an agent, failed or not, each listing at most
163
+ # MAX_LISTED_ERRORS distinct entries, each cut to MAX_ERROR_LENGTH
164
+ # characters, so they stay short:
165
+ # - the error items Codex reports without failing the turn (e.g.
166
+ # "Model metadata for `x` not found"), which may explain a weak
167
+ # report;
168
+ # - the MCP tool calls that failed, such as those refused because
169
+ # codex exec never asks for approval ("MCP tool call requires
170
+ # approval, but approval policy is never"), whose results the
171
+ # report may lack.
172
+ module_function def warnings(jsonl)
173
+ errors = nonblank(completed_items(jsonl, 'error').map { |item| item['message'] }).uniq
174
+ calls = failed_calls(completed_items(jsonl, 'mcp_tool_call').select do |item|
175
+ item['status'] == 'failed'
176
+ end)
177
+ warnings = []
178
+ unless errors.empty?
179
+ warnings << listing("Codex reported #{errors.size == 1 ? 'an error' : 'errors'}",
180
+ errors)
181
+ end
182
+ unless calls.empty?
183
+ warnings << listing("Codex MCP tool call#{'s' unless calls.size == 1} failed",
184
+ calls)
185
+ end
186
+ warnings
187
+ end
188
+
189
+ # A warning: label, then entries, at most MAX_LISTED_ERRORS of them.
190
+ module_function def listing(label, entries)
191
+ listed = entries.first(MAX_LISTED_ERRORS).map { |entry| shorten(entry, MAX_ERROR_LENGTH) }
192
+ listed << "and #{entries.size - listed.size} more" if entries.size > listed.size
193
+ "#{label}: #{listed.join('; ')}"
194
+ end
195
+
196
+ # Failed MCP tool calls as distinct "server.tool (reason)" entries.
197
+ module_function def failed_calls(calls)
198
+ calls.map do |call|
199
+ server, name = nonblank([call['server']]).first, nonblank([call['tool']]).first
200
+ tool = name ? [server, name].compact.join('.') : 'unknown tool'
201
+ error = call['error']
202
+ reason = error['message'] if error.is_a?(Hash)
203
+ reason.is_a?(String) && !reason.strip.empty? ? "#{tool} (#{reason.strip})" : tool
204
+ end.uniq
205
+ end
206
+
207
+ MAX_LISTED_ERRORS = 5
208
+ MAX_ERROR_LENGTH = 200
209
+
210
+ # text, cut to max characters with "..." if longer.
211
+ module_function def shorten(text, max)
212
+ text.length > max ? "#{text[0, max]}..." : text
213
+ end
214
+
215
+ # The values that are nonblank strings, stripped.
216
+ module_function def nonblank(values)
217
+ values.grep(String).map(&:strip).reject(&:empty?)
218
+ end
219
+ end
220
+ end
221
+ end