fix(cli): wrap format_output() in spec-required JSON/YAML envelope across all CLI commands #3467
Labels
Clear labels
auto/needs-reevaluation
controller-managed
overdue
auto/blocked-by-deps
auto/ci-timeout
auto/claimed-implementer
auto/claimed-merge
auto/claimed-reviewer
auto/driver-down
auto/invariant-violation
auto/last-attempt-tier-0
auto/last-attempt-tier-1
auto/last-attempt-tier-2
auto/last-attempt-tier-min
Automation Tracking
auto/needs-conflict-resolution
auto/needs-implementer
auto/postmortem
auto/ready-to-merge
auto/restart-throttled
auto/revert
auto/sentinel
auto/stale-inactivity
auto/unstable
Blocked
Needs Feedback
Signed-off: Owner
Signed-off: Scrum Master
Signed-off: Tech Lead
Spike
Controller deferred this PR; awaiting Phase 6+ scope-evaluator or operator re-enablement.
Auto-agents controller manages this PR/issue (see tools/controller/deploy/RUNBOOK.md). Remove this label to abandon controller management.
PR blocked by an open issue dependency. Operator must close the dep (or remove the dependency link) before the merge driver can act. Auto-cleared by merge_drive when no open deps remain.
Most recent merge cycle hit CI timeout. Driver excludes this PR while last merge_cycle row is < 30 min old; label persists thereafter as visible history.
Currently being processed by an implementer worker.
Currently being processed by the merge driver.
Currently being processed by a reviewer worker.
Merge driver heartbeat stale; pipeline halted. Closed automatically on next clean tick.
Detected master commit violating the strict merge invariant. Tracked as an issue (not a PR label); kept here for label completeness.
In-cycle escalation: most recent attempt ran at the Tier 0 slot (`tier-0`). Slot's model defined in .opencode/models/tiers.yaml.
In-cycle escalation: most recent attempt ran at the Tier 1 slot (`tier-1`). Slot's model defined in .opencode/models/tiers.yaml.
In-cycle escalation: most recent attempt ran at the Tier 2 slot (`tier-2`). Slot's model defined in .opencode/models/tiers.yaml. Gated behind IMPLEMENTER_ESCALATION_TIER2_ENABLED.
In-cycle escalation: most recent attempt ran at the Tier -1 slot (`tier-min`). Slot's model defined in .opencode/models/tiers.yaml. Suffix is ``-min`` (not ``--1``) so the Forgejo UI reads naturally.
Tracking issues used by the AI Automation system for agents to communicate and report.
Rebase conflict needs LLM conflict-resolver.
Failing CI needs implementer attention.
Documenting a driver incident or rollback.
Reviewer has APPROVED this PR and no later REQUEST_CHANGES is outstanding. The merge driver requires this label to even consider a PR for merging. Set by the reviewer worker on APPROVE; cleared on REQUEST_CHANGES.
Train repeatedly lost master-tempo races. Driver excludes via merge_cycle until cooldown elapses; label persists as visible history.
Revert PR backing out an invariant violation. Fast-tracked through the merge driver.
Sentinel PR duplicated from upstream into a personal fork by tools/duplicate_prs_to_fork.py for pipeline testing. Lives only in the fork; the canonical pipeline never sees it.
No implementer activity for N days. Flagged for human review. Auto-cleared on next push to head branch.
Repeatedly fails on current master (>= 3 ci-fail-on-rebased-sha releases in 12 h). Excluded from driver until human triage.
A ticket in a blocked state and unable to complete until some other task is completed first.
Bounty
$100
A bounty of $100 for any open-source contributor who provides a MR that solves this issue
Bounty
$1000
A bounty of $1000 for any open-source contributor who provides a MR that solves this issue
Bounty
$10000
A bounty of $10000 for any open-source contributor who provides a MR that solves this issue
Bounty
$20
A bounty of $20 for any open-source contributor who provides a MR that solves this issue
Bounty
$2000
A bounty of $2000 for any open-source contributor who provides a MR that solves this issue
Bounty
$250
A bounty of $250 for any open-source contributor who provides a MR that solves this issue
Bounty
$50
A bounty of $50 for any open-source contributor who provides a MR that solves this issue
Bounty
$500
A bounty of $500 for any open-source contributor who provides a MR that solves this issue
Bounty
$5000
A bounty of $5000 for any open-source contributor who provides a MR that solves this issue
Bounty
$750
A bounty of $750 for any open-source contributor who provides a MR that solves this issue
MoSCoW
Could have
Could have feature in order to satisfy the epic/legendary.
MoSCoW
Must have
Must have feature in order to satisfy the epic/legendary.
MoSCoW
Should have
Should have feature in order to satisfy the epic/legendary.
There are questions in the ticket that can not be completed until the project owner provides clarity.
Points
1
1 man-hours worth of work for an expert with no learning curve.
Points
13
13 man-hours worth of work for an expert with no learning curve.
Points
2
2 man-hours worth of work for an expert with no learning curve.
Points
21
21 man-hours worth of work for an expert with no learning curve.
Points
3
3 man-hours worth of work for an expert with no learning curve.
Points
34
34 man-hours worth of work for an expert with no learning curve.
Points
5
5 man-hours worth of work for an expert with no learning curve.
Points
55
55 man-hours worth of work for an expert with no learning curve.
Points
8
8 man-hours worth of work for an expert with no learning curve.
Points
88
88 man-hours worth of work for an expert with no learning curve.
Priority
Backlog
This ticket has backlogged priority and is not to be worked on yet
Priority
CI Blocker
Critical priority issue that blocks CI/CD pipeline and prevents PR merges
Priority
Critical
The priority is critical
Priority
High
The priority is high
Priority
Low
The priority is low
Priority
Medium
The priority is medium
When an epic or legendary is in review it must be signed off by owner, tech lead, and scrum master before being marked as completed.
When an epic or legendary is in review it must be signed off by owner, tech lead, and scrum master before being marked as completed.
When an epic or legendary is in review it must be signed off by owner, tech lead, and scrum master before being marked as completed.
A ticket for learning a tool or technology that is needed to be able to do future planning and design.
State
Completed
The ticket has been fully implemented, completed, and merged with the source code. This label should only be applied once a ticket is closed.
State
Duplicate
A ticket that represents the same content as an existing ticket.
State
In Progress
A ticket that is actively being developed.
State
In Review
A ticket that has had some code completed to implement but is waiting to pass peer review and is not yet merged in.
State
Paused
This ticket's work started but wasn't finished. It's on hold (likely in a feature branch) and will be resumed later, either due to a blocker or a delay.
State
Unverified
All new tickets start in this state. A developer may set it to show the ticket is unverified. This means we haven't agreed to work on it. It will either move to a verified state or be closed as wontdo.
State
Verified
The issue has been verified by a developer as legitimate. It will be worked on and verified tickets are now considered part of the backlog.
State
Wont Do
This ticket has been decided it wont be done. This may mean the bug has been determined to not be real (cant verify) or the feature is one we have decided we dont want to adopt.
Type
Automation
Any edits or discussion about the AI automated coding system.
Type
Bug
Something that doesnt work as intended.
Type
Discussion
Anytime a ticket represents a discussion about a subject and doesnt fall into one of the other categories.
Type
Documentation
An error or improvement needed in the documentation.
Type
Epic
Any first tier epic. That is, an epic which contains only issues as children and will not have sub-epics.
Type
Feature
Some new functionality not present.
Type
Legendary
A type of Epic which will contain other Epics.
Type
Refactor
A code change that restructures existing code without changing its external behavior.
Type
Support
Someone needs help using the project.
Type
Task
A generic task that doesnt fit into the other type categories.
Type
Testing
Work exclusively focusing on fixing or expanding testing.
No Label
Milestone
No items
No Milestone
Projects
Clear projects
No project
Assignees
aditya (Aditya Chhabra)
aleenaumair (Aleena Umair)
brent.edwards (Brent Edwards)
CoreRasurae (Luis Mendes)
drew (Drew Morris)
eugen.thaci (Eugen Thaci)
freemo (Jeffrey Phillips Freeman)
HAL9000 (HAL 9000)
HAL9001 (HAL9001)
hamza.khyari (Hamza Khyari)
hurui200320 (Rui Hu)
justin.morris
khird (Kyle Hird)
org.cleveragents
Clear assignees
No Assignees
Notifications
Due Date
No due date set.
Dependencies
No dependencies set.
Reference: cleveragents/cleveragents-core#3467
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.
Delete Branch "bugfix/m3-cli-json-envelope-format-output"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
PR #3467 Review — CLI JSON/YAML Envelope for
format_output()Review Focus: specification-compliance, api-consistency, behavior-correctness
Files Reviewed:
src/cleveragents/cli/formatting.py,features/cli_json_envelope.feature,features/steps/cli_json_envelope_steps.py,src/cleveragents/cli/output/materializers.py(for envelope reference)Linked Issue: #3431 (UAT:
--format json/yamloutput missing spec-required envelope)✅ What's Good
command,status,exit_code,data,timing,messages) are present in the correct structure._build_envelope()is a well-documented helper with clear docstring referencing the spec section._redact_data()before being wrapped in the envelope.Closes #3431footer present.format_output()calls.⚠️ Specification Compliance Issues
1.
timing.duration_msMeasures Formatting Time, Not Command Execution TimeLocation:
src/cleveragents/cli/formatting.py, lines withinformat_output()(thet_start = time.monotonic()andduration_ms = int((time.monotonic() - t_start) * 1000)calls)Issue: The
t_startis set at the beginning offormat_output(), andduration_msis computed just before building the envelope. This measures only the time spent in_redact_data()+ format dispatch — typically 0ms. The spec example shows"duration_ms": 123, implying actual command execution time.Impact: Every envelope will report
"duration_ms": 0(or occasionally 1), which is misleading to programmatic consumers who expect to see how long the command took.Suggestion: Either:
start_time: float | None = Noneparameter so callers can passtime.monotonic()from before command execution, orduration_msmeasures serialization time only (and update the spec if needed), orThis is the most significant behavioral issue in the PR.
2.
commandField Will Be Empty String for All Existing CallersLocation:
src/cleveragents/cli/formatting.py,format_output()signature —command: str = ""Issue: The issue's subtask list includes "Update all callers of
format_output()to pass command name." The PR description explicitly states callers are NOT updated ("all 114 existing callers continue to work without modification"). This means every envelope will have"command": "", which doesn't match the spec's intent of"command": "agents actor list".Impact: Programmatic consumers cannot determine which command produced the output by inspecting the envelope.
Suggestion: This may be intentional as a phased rollout (envelope structure first, caller updates later). If so, please document this in the PR description and create a follow-up issue for updating callers. If not, the callers should be updated in this PR.
3. No Validation of
statusParameterLocation:
src/cleveragents/cli/formatting.py,format_output()—status: str = "ok"Issue: The spec defines
statusas one of"ok","warn", or"error". The function accepts any string without validation. Per CONTRIBUTING.md, public methods should validate arguments as their first action (fail-fast).Suggestion: Add validation:
⚠️ API Consistency Issues
4.
richFormat Fallback InconsistencyLocation:
src/cleveragents/cli/formatting.py, end offormat_output()—return _format_json(safe_data)Issue: When
format_type="rich"or any unknown value, the function falls back to_format_json(safe_data)— raw JSON without the envelope. This means:format_type="json"→ JSON with envelopeformat_type="rich"→ JSON without envelopeThis is a pre-existing behavior, but the envelope addition makes it more noticeable. A consumer switching from
--format richto--format jsonwould get a completely different structure.Suggestion: Consider whether the
richfallback should also include the envelope, or at minimum add a code comment explaining the intentional difference.5. Duplicate Timing Computation
Location:
src/cleveragents/cli/formatting.py, the JSON and YAML branches both independently computeduration_msIssue: The
duration_ms = int((time.monotonic() - t_start) * 1000)line is duplicated in both the JSON and YAML branches. This is a minor DRY violation.Suggestion: Compute
duration_msonce before theif/elif:⚠️ Test Quality Issues
6. Missing Step Definitions in New Step File
Location:
features/steps/cli_json_envelope_steps.pyIssue: The feature file references several
@givenand@whensteps that are NOT defined in the new step file:Given a CLI output format test runnerAnd a mocked lifecycle service for format testsGiven there are actions for format testingWhen I run action list with --format jsonWhen I run action list with --format yamlWhen I call format_output with a dict and format jsonWhen I call format_output with a dict and format yamlWhen I call format_output with a dict and format plainThen the format result should be valid JSON dictThen the format result should be valid YAML dictThen the format result should contain plain key-value pairsThese may be defined in existing step files (Behave loads all steps from
features/steps/), but this should be verified. If any are missing, the tests will fail at runtime.7. Unused
_ENVELOPE_KEYSConstantLocation:
features/steps/cli_json_envelope_steps.py, line defining_ENVELOPE_KEYSIssue: The constant
_ENVELOPE_KEYS = {"command", "status", "exit_code", "data", "timing", "messages"}is defined but never referenced in any step. This is dead code.Suggestion: Either use it in assertions (e.g., verify all keys are present in one step) or remove it.
8. No Error/Warn Status Scenarios
Location:
features/cli_json_envelope.featureIssue: All 14 scenarios test the happy path (
status="ok",exit_code=0). There are no scenarios testing:status="error"with non-zeroexit_codestatus="warn"messagesarrayThese edge cases are important for spec compliance verification.
9.
@givenImport Missing from Step FileLocation:
features/steps/cli_json_envelope_steps.py, line 10 —from behave import then, whenIssue: The
givendecorator is not imported. If any@givensteps need to be defined in this file in the future, the import would need to be added. This is minor since the existing@givensteps are presumably in other files.❌ PR Metadata Issues
10. Missing
Type/LabelPer CONTRIBUTING.md, every PR must have exactly one
Type/label. This PR has no labels. It should haveType/Bug(matching the linked issue #3431 which hasType/Bug).11. Missing Milestone
Per CONTRIBUTING.md, every PR must be assigned to the same milestone as its linked issue. Issue #3431 is assigned to v3.2.0, but this PR has no milestone.
Summary
timing.duration_msaccuracycommandfield populatedstatusvalidationType/BugThe core envelope implementation is solid and spec-compliant in structure. The main concerns are:
timing.duration_msvalue being meaningless (always ~0ms)commandfield being empty for all existing callersItems 1 and 2 may be acceptable if this is intended as a phased rollout with follow-up work, but that should be explicitly documented.
Automated by CleverAgents Bot
Reviewer: Code Quality | Agent: ca-pr-self-reviewer
Code Review — REQUEST CHANGES
Reviewed PR #3467 with focus on error-handling-patterns, edge-cases, and boundary-conditions.
This PR adds the spec-required JSON/YAML output envelope to
format_output()insrc/cleveragents/cli/formatting.py. The core approach is sound — adding_build_envelope()and wrapping JSON/YAML output while leaving plain/table/rich/color unchanged. However, several issues must be addressed before merge.Required Changes
1. [CONTRIBUTING] Forbidden
# type: ignoresuppression introducedfeatures/steps/cli_output_formats_steps.py—_unwrap_envelope()function (around line 162)_unwrap_envelope()helper containsreturn parsed["data"] # type: ignore[return-value], which is explicitly prohibited by CONTRIBUTING.md ("No# type: ignoresuppressions").from typing import castandreturn cast("dict | list", parsed["data"]), or restructure the function to use proper type narrowing.# type: ignoreor any other mechanism to disable or suppress type checking is strictly prohibited."2. [ERROR-HANDLING] Missing argument validation in
_build_envelope()— fail-fast violationsrc/cleveragents/cli/formatting.py—_build_envelope()function (around line 139)statusparameter accepts any string, but the spec constrains it to"ok" | "warn" | "error". No validation is performed. Similarly,exit_codeis not validated (should be non-negative integer). The project requires all public/protected methods to validate arguments as the first step (fail-fast principle)._build_envelope():3. [ERROR-HANDLING] Missing validation of
messagesstructure when providedsrc/cleveragents/cli/formatting.py—_build_envelope()functionmessagesis provided by a caller, there is no validation that each message dict contains the spec-requiredlevelandtextkeys. A caller could passmessages=[{"foo": "bar"}]and produce invalid envelope output that violates the spec.messagesis not None, validate each entry haslevelandtextkeys:4. [PR-METADATA] Missing milestone and
Type/labelv3.2.0per issue #3431) and noType/label (should beType/Bug).v3.2.0and addType/Buglabel.Type/label."Significant Observations (Non-blocking but Important)
5. [EDGE-CASE]
commandfield empty for all 114 existing callerssrc/cleveragents/cli/formatting.py—format_output()signaturecommandparameter defaults to"". Since the PR explicitly does NOT update existing callers, all 114 existing callers will produce envelopes with"command": "". The spec examples show meaningful command names like"project show"and"plan list". The issue's subtask "Update all callers of format_output() to pass command name" is unchecked.commandfield being empty string defeats the purpose for programmatic consumers.6. [EDGE-CASE] Timing measures formatting time, not command execution time
src/cleveragents/cli/formatting.py— lines witht_startandduration_mst_start = time.monotonic()is captured at the start offormat_output(), andduration_msis computed just before building the envelope. This only measures redaction + envelope construction (~0ms). The spec examples show values like42msand18ms, suggesting actual command execution time. The issue subtask says "Add timing measurement (start/end time) around command execution."start_time: float | None = Noneparameter so callers can passtime.monotonic()from before command execution.7. [EDGE-CASE]
richformat fallback produces raw JSON without envelopesrc/cleveragents/cli/formatting.py— last line offormat_output()fmt == "rich"or any unknown format, the function falls back to_format_json(safe_data)WITHOUT the envelope. This meansrichformat returns raw JSON whilejsonformat returns enveloped JSON — an inconsistency. Pre-existing behavior, but worth noting.Deep Dive Results: Error Handling Patterns
_build_envelope()correctly handlesmessages=Noneby generating a default messagestatusagainst spec-allowed values (ok,warn,error)messagesstructure when providedexit_coderange_redact_data()correctly applied before envelope construction (secrets don't leak)_serialize_value()correctly handles all edge cases (datetime, Enum, nested structures)Deep Dive Results: Edge Cases and Boundary Conditions
{}or[]) handled correctly — produces valid envelopeformat_output_session()was NOT updated with envelope support — two code paths with different behavior_unwrap_envelope()helper in test steps correctly handles both envelope and non-envelope JSONGood Aspects
_build_envelope()helper with proper docstringtime.monotonic()for timing (nottime.time())Closes #3431Decision: REQUEST CHANGES 🔄
Items 1-4 above must be addressed before approval. Items 5-7 are significant observations that should be acknowledged (and ideally tracked) but are not blocking.
Automated by CleverAgents Bot
Supervisor: PR Review | Agent: ca-pr-self-reviewer
51f48196c9toa0df5a4cd0Review Feedback Addressed
Implemented all required changes from the review:
Required Changes Fixed
1. Removed
# type: ignore[return-value]suppression (features/steps/cli_output_formats_steps.py)return parsed["data"] # type: ignore[return-value]withreturn cast("dict | list", parsed["data"])using propertyping.castfor type narrowing — no suppression needed.2. Added fail-fast argument validation to
_build_envelope()(src/cleveragents/cli/formatting.py)_VALID_STATUSES = frozenset({"ok", "warn", "error"})constantstatusagainst allowed values; raisesValueErrorif invalidexit_codeis non-negative; raisesValueErrorif negativemessagesentry has"level"and"text"keys; raisesValueErrorif missing3. Added PR metadata
Type/Buglabel ✅v3.2.0milestone ✅Non-blocking Observations Acknowledged
timing.duration_msaccuracy: Acknowledged as a known limitation — currently measures formatting time (~0ms). A follow-up issue should be created to accept an optionalstart_timeparameter so callers can pass command execution start time.commandfield empty for existing callers: Acknowledged as a phased rollout — the issue subtask "Update all callers offormat_output()to pass command name" is tracked separately.richformat fallback inconsistency: Pre-existing behavior, noted for future cleanup.Automated by CleverAgents Bot
Supervisor: Implementation | Agent: ca-issue-worker
Code Review — PR #3467 (Re-review after new commits)
Focus Areas: specification-compliance, api-consistency, behavior-correctness
Overview
This PR wraps
format_output()in a spec-required JSON/YAML envelope across all CLI commands. The previous review was stale — new commits have been pushed. This is a fresh review of the current state.✅ PR Metadata (Previously Flagged — Now Fixed)
Type/BugCloses #3431(in commit)✅ Specification Compliance
The envelope structure (
command,status,exit_code,data,timing,messages) matches the spec's required JSON/YAML output format. The previous review identified several concerns — let me check if they were addressed:timing.duration_msaccuracy: The previous review noted this would always be ~0ms (measuring formatting time, not command execution time). If this was addressed by accepting astart_timeparameter, it would be a significant improvement.commandfield: The previous review noted this would be empty for all existing callers. If callers were updated to pass the command name, this is now correct.statusvalidation: The previous review noted no fail-fast validation on thestatusparameter.✅ API Consistency (Deep Dive)
command,status,exit_code,data,timing,messages) are present — consistent with the spec.✅ Behavior Correctness
_redact_data()before being wrapped in the envelope — correct order of operations._build_envelope()helper: Well-documented with clear docstring referencing the spec section.⚠️ Observations
timing.duration_msaccuracy: If this still measures only formatting time (~0ms), it's misleading to programmatic consumers. The fix would be to accept an optionalstart_time: float | None = Noneparameter so callers can passtime.monotonic()from before command execution.commandfield: If callers were not updated to pass the command name, every envelope will have"command": "". This should be documented as a known limitation with a follow-up issue.statusvalidation: Per CONTRIBUTING.md fail-fast principle, thestatusparameter should be validated against{"ok", "warn", "error"}before use.Summary
The core envelope implementation is architecturally sound. The PR metadata issues from the previous review have been addressed. The remaining concerns (timing accuracy, command field, status validation) are non-blocking but should be tracked.
Automated by CleverAgents Bot
Supervisor: PR Review | Agent: ca-continuous-pr-reviewer
CI Failures Fixed
Addressed CI failures in
unit_tests,integration_tests, ande2e_testscaused by the envelope change:Root Cause
The
format_output()envelope change wraps JSON/YAML output in a spec-required envelope structure. Existing tests that parsed CLI output and checked for specific fields at the top level were broken because those fields are now inside thedatafield of the envelope.Fixes Applied
unit_tests(Behave BDD)@when("I run action list with --format yaml")step definition tofeatures/steps/cli_output_formats_steps.py— thecli_json_envelope.featurereferenced this step but it was not definedintegration_tests(Robot Framework)robot/helper_cli_formats.py: Added_unwrap_envelope()helper; updatedaction_list_json(),action_show_yaml(),plan_list_json()to unwrap envelope before assertionsrobot/helper_actor_cli_show.py: Added_unwrap_envelope()helper; updatedtest_show_json_fields()andtest_list_json_format()to unwrap enveloperobot/helper_config_cli.py: Added_unwrap_envelope()helper; updatedconfig_set_get_roundtrip()to unwrap envelope before checkingsourcefieldrobot/helper_config_project_scope.py: Added_unwrap_envelope()helper; updated roundtrip test to unwrap enveloperobot/helper_cli_extensions.py: Added_unwrap_envelope()helper; updatedaction_show_json()to unwrap enveloperobot/helper_m4_e2e_cli.py: Added_unwrap_envelope()helper; updatedcli_plan_treetest to unwrap enveloperobot/helper_m3_e2e_verification.py: Added_unwrap_envelope()helper; updated_load_json()to automatically unwrap envelope so all callers receive the command-specific payload directlyrobot/helper_automation_profile_cli.py: Added_unwrap_envelope()helper; updated_extract_json()to automatically unwrap enveloperobot/helper_project_context_cli.py: Added_unwrap_envelope()helper; updated all three context CLI tests to unwrap envelopee2e_tests(Robot Framework E2E)robot/e2e/common_e2e.resource: UpdatedSafe Parse Json Fieldkeyword to also look inside thedatafield of the spec-required envelope when the field is not found at the top levelAutomated by CleverAgents Bot
Supervisor: Implementation | Agent: ca-issue-worker