Skip to content

feat: unify output surface contract for flags, formats and errors#1882

Open
sang-neo03 wants to merge 1 commit into
mainfrom
feat/output-surface-contract
Open

feat: unify output surface contract for flags, formats and errors#1882
sang-neo03 wants to merge 1 commit into
mainfrom
feat/output-surface-contract

Conversation

@sang-neo03

@sang-neo03 sang-neo03 commented Jul 14, 2026

Copy link
Copy Markdown
Collaborator

Summary

The CLI output and error surface was inconsistent, so an agent could not predict a command's behavior from its declaration: --json was a dead flag on api/service yet worked (with differing priority) on shortcuts and auth scopes; --format pretty was advertised and handled differently across families; top-level unknown commands returned prose without structured suggestions; and flag/argument errors were classified by matching English text fragments, which misclassified flag-group errors as internal faults (exit 5). This PR unifies the whole surface into one predictable contract.

Changes

  • Add internal/output/capabilities.go (FormatCapabilities) as the single source for --format usage text, shell completion, --json shorthand resolution and format validation; cmd/api/api.go, cmd/service/service.go, cmd/auth/scopes.go and shortcuts/common/runner.go now resolve through it, with explicit --format winning over --json
  • Render --format pretty as indented JSON via its own FormatPretty case in internal/output/format.go and format_type.go, instead of aliasing it to table
  • Collapse flag-parse error handling into a single root FlagErrorFunc in cmd/root.go that classifies pflag typed errors; delete the mail and sheets local hooks (shortcuts/mail/flag_suggest.go, shortcuts/sheets/flag_ergonomics.go, shortcuts/register.go)
  • Type cobra argument, required-flag and flag-group errors at their validation stage via installCobraValidationGuards in cmd/root.go, and remove the cobraUsageErrorMarkers / isCobraUsageError text matching
  • Return structured suggestions for root and group unknown commands (cmd/root.go, cmd/build.go)
  • Mark pure group nodes as non-runnable in internal/qualitygate/cmd/manifest-export/collect.go

Known limitation

Warning

--format pretty / table is only partially delivered for shortcuts.
api, service and auth scopes honor the selected format, but a subset of
shortcuts that emit their result through the framework default ctx.Out
still return the JSON envelope even though their help/completion advertise
pretty / table. Their format capability is injected uniformly by the
framework instead of declared per command, so an advertised --format table
is accepted but not actually rendered.

This is a pre-existing gap, not a regression — those shortcuts behaved the
same before this PR, which additionally fixes api/service and turns silent
fallback into an explicit error. Fully closing it means declaring each
shortcut's real format capability across ~260 ctx.Out call sites in a dozen
domains (base, sheets, drive, mail, ...); that shares the output-emitter area
tracked separately and is deferred to that follow-up.

Test Plan

  • make unit-test passed
  • skipped: validate / local-eval / acceptance-reviewer — this output-surface change was reviewed and verified directly rather than through the full dev pipeline; go build ./... and go vet ./... are clean and manual verification below covers each behavior
  • manual verification (branch binary):
    • api GET <path> --dry-run --format pretty --json--json no longer overrides an explicit format
    • auth scopes --format pretty --json — prints human text (explicit --format wins)
    • api GET <path> --format bogus — typed validation error, exit 2 (was warning + json)
    • imm — structured params[].suggestions: ["im"], exit 2
    • sheets +csv-put --url <u> --sheet-id <s> --csv a,b — flag-group error is validation/exit 2 with params, was internal/exit 5
    • mail +send --tos <addr> — still suggests --to

Related Issues

N/A

Summary by CodeRabbit

  • New Features
    • Added consistent output format handling across API, service, authentication, and shortcut commands, including --json shorthand and data-driven --format help/completion.
    • Added a pretty format for readable, indented JSON, including paginated results.
  • Bug Fixes
    • Invalid output formats now return clear validation errors instead of silently falling back to JSON.
    • Improved unknown command and flag errors with structured messages and relevant suggestions.
    • Pretty-formatted scope listings now appear on standard output.

@sang-neo03 sang-neo03 requested a review from liangshuo-1 as a code owner July 14, 2026 09:19
@github-actions github-actions Bot added domain/calendar PR touches the calendar domain domain/ccm PR touches the ccm domain domain/mail PR touches the mail domain size/L Large or sensitive change across domains or core paths labels Jul 14, 2026
@coderabbitai

coderabbitai Bot commented Jul 14, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

The CLI now centralizes output-format resolution, supports explicit pretty JSON rendering, validates unsupported formats, and converts Cobra parsing and argument failures into structured validation errors. Service-specific flag suggestion hooks are removed, and pure navigation groups are excluded from runnable command manifests.

Changes

Output format resolution and rendering

Layer / File(s) Summary
Format capabilities and pretty rendering
internal/output/*
Adds shared format capabilities, FormatPretty, normalized resolution, dynamic usage/completion names, and indented JSON formatting tests.
API, service, and auth format wiring
cmd/api/*, cmd/auth/*, cmd/service/*, shortcuts/calendar/calendar_test.go
Applies shared format resolution and JSON shorthand precedence to commands, adds pretty pagination handling, and updates related tests.
Shortcut output normalization
shortcuts/common/*, shortcuts/mail/mail_json_shorthand_test.go
Validates shortcut formats before execution, preserves JSON envelopes for pretty output, and replaces warning-based fallback with typed validation errors.

Structured Cobra validation

Layer / File(s) Summary
Cobra validation guards and typed errors
cmd/build.go, cmd/root.go, go.mod
Installs guards for argument, required-flag, flag-group, unknown-flag, and unknown-subcommand validation, while treating remaining untyped errors as internal errors.
Validation behavior coverage
cmd/*_test.go
Adds coverage for structured parameters, suggestions, flag-group reasons, validation envelopes, and validation exit codes.
Removal of service-specific flag hooks
shortcuts/register.go, shortcuts/register_test.go, shortcuts/mail/*, shortcuts/sheets/*
Removes mail and sheets-specific unknown-flag handlers and their tests while retaining remaining shortcut registration behavior.

Command manifest classification

Layer / File(s) Summary
Pure-group runnable classification
internal/qualitygate/cmd/manifest-export/*
Marks pure navigation groups as non-runnable in exported manifests and verifies the approval group classification.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant User
  participant Cobra
  participant ValidationGuards
  participant Command
  User->>Cobra: Provide flags and arguments
  Cobra->>ValidationGuards: Parse and validate input
  ValidationGuards-->>Cobra: Structured validation error or valid input
  Cobra->>Command: Execute validated command
  Command-->>User: Output or typed error envelope
Loading

Possibly related PRs

Suggested labels: domain/base

Suggested reviewers: liangshuo-1, liangshuo-1

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 29.41% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title concisely reflects the main change: unifying CLI output, flag, and error handling.
Description check ✅ Passed The description matches the required template and includes summary, changes, test plan, and related issues.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/output-surface-contract

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@codecov

codecov Bot commented Jul 14, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 72.20077% with 72 lines in your changes missing coverage. Please review.
✅ Project coverage is 74.66%. Comparing base (37d490a) to head (041bf48).

Files with missing lines Patch % Lines
cmd/root.go 76.47% 18 Missing and 14 partials ⚠️
shortcuts/common/runner.go 67.50% 10 Missing and 3 partials ⚠️
cmd/api/api.go 45.45% 7 Missing and 5 partials ⚠️
cmd/service/service.go 54.54% 6 Missing and 4 partials ⚠️
cmd/auth/scopes.go 58.33% 3 Missing and 2 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1882      +/-   ##
==========================================
- Coverage   74.66%   74.66%   -0.01%     
==========================================
  Files         877      877              
  Lines       91731    91737       +6     
==========================================
+ Hits        68494    68497       +3     
+ Misses      17926    17911      -15     
- Partials     5311     5329      +18     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@github-actions

github-actions Bot commented Jul 14, 2026

Copy link
Copy Markdown

🚀 PR Preview Install Guide

🧰 CLI update

npm i -g https://pkg.pr.new/larksuite/cli/@larksuite/cli@041bf48e0efca620ff055315b7fe39c7bc22ea04

🧩 Skill update

npx skills add larksuite/cli#feat/output-surface-contract -y -g

@sang-neo03 sang-neo03 force-pushed the feat/output-surface-contract branch from 108f371 to f560b1a Compare July 14, 2026 09:44

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@cmd/auth/auth_test.go`:
- Around line 358-378: Update TestAuthScopesCmd_JSONShorthand and the adjacent
test case around the same command to call t.Setenv("LARKSUITE_CLI_CONFIG_DIR",
t.TempDir()) before invoking cmdutil.TestFactory, ensuring each test uses an
isolated temporary CLI configuration directory.

In `@cmd/root.go`:
- Around line 724-753: The typed flag error tests in cmd/flag_suggest_test.go
cover neither the InvalidSyntaxError nor InvalidValueError branches of
typedFlagParseError. Add focused tests for both paths, verifying the returned
validation error includes the expected InvalidParam name and reason while
preserving the existing error behavior.

In `@internal/output/capabilities_test.go`:
- Around line 32-38: Update the wantErr assertion in the Resolve() test to
validate the ValidationError subtype as well as Param. After errors.As extracts
validationErr, assert both typed metadata fields match the expected
format-validation subtype and "--format" parameter, preserving the existing
failure message and early return behavior.

In `@shortcuts/common/runner.go`:
- Around line 1216-1223: Update shortcutFormatSupportsJSON to treat a format
flag with no enum values as JSON-supported when its default format is "json",
matching shortcutFormatCapabilities; preserve the existing enum-membership check
when choices are defined and the current true result when no format flag exists.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: cfea247e-676e-4ca7-8848-26753b784af8

📥 Commits

Reviewing files that changed from the base of the PR and between 37d490a and f560b1a.

📒 Files selected for processing (32)
  • cmd/api/api.go
  • cmd/api/api_test.go
  • cmd/auth/auth_test.go
  • cmd/auth/scopes.go
  • cmd/auth/scopes_test.go
  • cmd/build.go
  • cmd/build_test.go
  • cmd/flag_suggest_test.go
  • cmd/root.go
  • cmd/root_test.go
  • cmd/service/service.go
  • cmd/service/service_test.go
  • cmd/unknown_subcommand_test.go
  • go.mod
  • internal/output/capabilities.go
  • internal/output/capabilities_test.go
  • internal/output/format.go
  • internal/output/format_test.go
  • internal/output/format_type.go
  • internal/output/format_type_test.go
  • internal/qualitygate/cmd/manifest-export/collect.go
  • internal/qualitygate/cmd/manifest-export/main_test.go
  • shortcuts/calendar/calendar_test.go
  • shortcuts/common/runner.go
  • shortcuts/common/runner_format_universal_test.go
  • shortcuts/mail/flag_suggest.go
  • shortcuts/mail/flag_suggest_test.go
  • shortcuts/mail/mail_json_shorthand_test.go
  • shortcuts/register.go
  • shortcuts/register_test.go
  • shortcuts/sheets/flag_ergonomics.go
  • shortcuts/sheets/flag_ergonomics_test.go
💤 Files with no reviewable changes (5)
  • shortcuts/mail/flag_suggest.go
  • shortcuts/register.go
  • shortcuts/mail/flag_suggest_test.go
  • shortcuts/register_test.go
  • shortcuts/sheets/flag_ergonomics_test.go

Comment thread cmd/auth/auth_test.go
Comment thread cmd/root.go
Comment thread internal/output/capabilities_test.go
Comment thread shortcuts/common/runner.go
Consolidate the CLI output/error contract so agents can predict behavior
from a command's declaration:

- --json / --format resolved through a single FormatCapabilities set;
  explicit --format wins over --json across api, service, shortcut and
  auth scopes
- --format pretty renders as indented JSON via its own Format case,
  no longer aliased to table
- a single root FlagErrorFunc classifies pflag typed errors; the mail
  and sheets local FlagErrorFunc hooks are removed
- cobra argument, required-flag and flag-group errors are typed at their
  validation stage; the usage-error text markers are removed
- root and group unknown commands return structured suggestions
- manifest-export marks pure group nodes as non-runnable
@sang-neo03 sang-neo03 force-pushed the feat/output-surface-contract branch from f560b1a to 041bf48 Compare July 14, 2026 11:04

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@shortcuts/common/runner_format_universal_test.go`:
- Around line 117-123: Update the error assertions in the test around errors.As
to call errs.ProblemOf(err) and assert the returned category, subtype, and param
metadata, including the existing --format expectation; retain the type assertion
only if needed for the test’s intended coverage.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: c94897fa-85a3-489d-96d0-9c27d073d7c3

📥 Commits

Reviewing files that changed from the base of the PR and between f560b1a and 041bf48.

📒 Files selected for processing (32)
  • cmd/api/api.go
  • cmd/api/api_test.go
  • cmd/auth/auth_test.go
  • cmd/auth/scopes.go
  • cmd/auth/scopes_test.go
  • cmd/build.go
  • cmd/build_test.go
  • cmd/flag_suggest_test.go
  • cmd/root.go
  • cmd/root_test.go
  • cmd/service/service.go
  • cmd/service/service_test.go
  • cmd/unknown_subcommand_test.go
  • go.mod
  • internal/output/capabilities.go
  • internal/output/capabilities_test.go
  • internal/output/format.go
  • internal/output/format_test.go
  • internal/output/format_type.go
  • internal/output/format_type_test.go
  • internal/qualitygate/cmd/manifest-export/collect.go
  • internal/qualitygate/cmd/manifest-export/main_test.go
  • shortcuts/calendar/calendar_test.go
  • shortcuts/common/runner.go
  • shortcuts/common/runner_format_universal_test.go
  • shortcuts/mail/flag_suggest.go
  • shortcuts/mail/flag_suggest_test.go
  • shortcuts/mail/mail_json_shorthand_test.go
  • shortcuts/register.go
  • shortcuts/register_test.go
  • shortcuts/sheets/flag_ergonomics.go
  • shortcuts/sheets/flag_ergonomics_test.go
💤 Files with no reviewable changes (5)
  • shortcuts/mail/flag_suggest.go
  • shortcuts/register.go
  • shortcuts/mail/flag_suggest_test.go
  • shortcuts/sheets/flag_ergonomics_test.go
  • shortcuts/register_test.go
🚧 Files skipped from review as they are similar to previous changes (22)
  • cmd/build.go
  • shortcuts/calendar/calendar_test.go
  • internal/output/format_type.go
  • internal/output/capabilities_test.go
  • internal/output/format_type_test.go
  • internal/qualitygate/cmd/manifest-export/main_test.go
  • cmd/auth/scopes.go
  • cmd/api/api_test.go
  • cmd/flag_suggest_test.go
  • shortcuts/sheets/flag_ergonomics.go
  • cmd/service/service.go
  • cmd/root_test.go
  • cmd/unknown_subcommand_test.go
  • internal/qualitygate/cmd/manifest-export/collect.go
  • cmd/auth/scopes_test.go
  • cmd/auth/auth_test.go
  • internal/output/capabilities.go
  • cmd/api/api.go
  • cmd/build_test.go
  • cmd/service/service_test.go
  • cmd/root.go
  • shortcuts/common/runner.go

Comment on lines +117 to +123
var validationErr *errs.ValidationError
if !errors.As(err, &validationErr) {
t.Fatalf("expected *errs.ValidationError, got %T: %v", err, err)
}
if validationErr.Param != "--format" {
t.Fatalf("param = %q, want --format", validationErr.Param)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Assert Category and Subtype via errs.ProblemOf.

As per coding guidelines, error-path tests must assert typed metadata via errs.ProblemOf (category / subtype / param). This test currently checks the Param field using errors.As, but it omits the required errs.ProblemOf assertions for Category and Subtype.

💡 Proposed fix to include full metadata assertions
 	var validationErr *errs.ValidationError
 	if !errors.As(err, &validationErr) {
 		t.Fatalf("expected *errs.ValidationError, got %T: %v", err, err)
 	}
 	if validationErr.Param != "--format" {
 		t.Fatalf("param = %q, want --format", validationErr.Param)
 	}
+
+	problem, ok := errs.ProblemOf(err)
+	if !ok {
+		t.Fatalf("error = %T, want typed errs problem carrier", err)
+	}
+	if problem.Category != errs.CategoryValidation {
+		t.Fatalf("category = %q, want %q", problem.Category, errs.CategoryValidation)
+	}
+	if problem.Subtype != errs.SubtypeInvalidArgument {
+		t.Fatalf("subtype = %q, want %q", problem.Subtype, errs.SubtypeInvalidArgument)
+	}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
var validationErr *errs.ValidationError
if !errors.As(err, &validationErr) {
t.Fatalf("expected *errs.ValidationError, got %T: %v", err, err)
}
if validationErr.Param != "--format" {
t.Fatalf("param = %q, want --format", validationErr.Param)
}
var validationErr *errs.ValidationError
if !errors.As(err, &validationErr) {
t.Fatalf("expected *errs.ValidationError, got %T: %v", err, err)
}
if validationErr.Param != "--format" {
t.Fatalf("param = %q, want --format", validationErr.Param)
}
problem, ok := errs.ProblemOf(err)
if !ok {
t.Fatalf("error = %T, want typed errs problem carrier", err)
}
if problem.Category != errs.CategoryValidation {
t.Fatalf("category = %q, want %q", problem.Category, errs.CategoryValidation)
}
if problem.Subtype != errs.SubtypeInvalidArgument {
t.Fatalf("subtype = %q, want %q", problem.Subtype, errs.SubtypeInvalidArgument)
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@shortcuts/common/runner_format_universal_test.go` around lines 117 - 123,
Update the error assertions in the test around errors.As to call
errs.ProblemOf(err) and assert the returned category, subtype, and param
metadata, including the existing --format expectation; retain the type assertion
only if needed for the test’s intended coverage.

Source: Coding guidelines

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

domain/calendar PR touches the calendar domain domain/ccm PR touches the ccm domain domain/mail PR touches the mail domain feature size/L Large or sensitive change across domains or core paths

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant