Open
feat(#440): --json-out 输出流契约——日志统一走 stderr + 全局 --log-stream/--quiet #89
grape_botAdd on 1 day ago
feat(#440): --json-out 输出流契约——日志统一走 stderr + 全局 --log-stream/--quiet #89
Open
grape_botAdd on 1 day ago
Merged fromfeat/issue-440intoldw
Total: 15 files changed+655-22
@@ -7,6 +7,7 @@ Issue refs point to the issue pipeline repo `grape-dev/grape` unless prefixed ot
7 7 
8### Added8### Added
9 9 
10+- Unified output-stream contract: every CLI log/warning goes through the single `grape_cli/logs.py` exit and lands on **stderr**, so `grape ... --json-out | jq` never breaks; new global `--log-stream stderr|stdout|off` and `--quiet` control the flow (default unchanged: stderr), and `--json-out` pins logs to stderr even if `--log-stream stdout` is given. Existing `warning:` / upgrade-notice text is byte-identical; `grape git` passthrough output stays verbatim and is documented as out of scope. (`test/test_output_stream.py`, `docs/grape-output-stream-contract.md`)(grape-cli#440)
10- `grape doctor`: one-shot environment self-check — token channels (session / user key / auth file), effective base_url probe, proxy env sanity, contract cache health, CLI version comparison; OK/WARN/FAIL per check with actionable hints; exit 1 on any FAIL (`--json-out` supported). Diagnosis only — no auto-fix.(#2662)11- `grape doctor`: one-shot environment self-check — token channels (session / user key / auth file), effective base_url probe, proxy env sanity, contract cache health, CLI version comparison; OK/WARN/FAIL per check with actionable hints; exit 1 on any FAIL (`--json-out` supported). Diagnosis only — no auto-fix.(#2662)
11- `--dry-run` on all write commands (POST/PUT/PATCH/DELETE): prints the redacted method/path/query/body preview at the single `ApiClient.request` exit and exits without sending — zero side effects on the server; new contract write endpoints inherit automatically.(#2662)12- `--dry-run` on all write commands (POST/PUT/PATCH/DELETE): prints the redacted method/path/query/body preview at the single `ApiClient.request` exit and exits without sending — zero side effects on the server; new contract write endpoints inherit automatically.(#2662)
12- CHANGELOG + tag-triggered release note skeleton (`scripts/gen_release_note.py`).(#2662)13- CHANGELOG + tag-triggered release note skeleton (`scripts/gen_release_note.py`).(#2662)
@@ -53,7 +53,7 @@ tokens leaking into shell history:
53- **Automatic auth injection** — Bearer token attached by default (client also supports `PRIVATE-TOKEN` / `?access_token=` channels).53- **Automatic auth injection** — Bearer token attached by default (client also supports `PRIVATE-TOKEN` / `?access_token=` channels).
54- **Native git passthrough** — `grape git` runs real `git`, auto-detects the repo, and injects a short-lived credential via `GIT_CONFIG` env vars — never on the command line, never on disk.54- **Native git passthrough** — `grape git` runs real `git`, auto-detects the repo, and injects a short-lived credential via `GIT_CONFIG` env vars — never on the command line, never on disk.
55- **Built-in `tasks wait`** — poll a task until a terminal state (`completed` / `failed` / `cancelled`).55- **Built-in `tasks wait`** — poll a task until a terminal state (`completed` / `failed` / `cancelled`).
56-- **Machine-readable output** — `--json-out` emits single-line JSON for workers and scripts.56+- **Machine-readable output** — `--json-out` emits single-line JSON for workers and scripts; logs and warnings go to **stderr** only, so `--json-out | jq` never breaks ([output stream contract](docs/grape-output-stream-contract.md)).
57- **Mode-aware command sets** — `GRAPE_CLI_MODE` (WORKER / USER / ALL) filters commands by token scope (dual / session-only / user-only).57- **Mode-aware command sets** — `GRAPE_CLI_MODE` (WORKER / USER / ALL) filters commands by token scope (dual / session-only / user-only).
58 58 
59## Install59## Install
@@ -146,6 +146,8 @@ grape commands [pattern] # list contract commands; pipe to filter: grape co
146grape refresh # force-fetch the newest OpenAPI contract and refresh the cache146grape refresh # force-fetch the newest OpenAPI contract and refresh the cache
147grape tasks wait --task-id 56 --timeout 120 --interval 3 # poll a task until terminal state147grape tasks wait --task-id 56 --timeout 120 --interval 3 # poll a task until terminal state
148grape --timeout 300 tasks current # request timeout (default 30s; git unaffected)148grape --timeout 300 tasks current # request timeout (default 30s; git unaffected)
149+grape --log-stream stderr|stdout|off <cmd> # where logs/warnings go (default stderr)
150+grape --quiet <cmd> # silence logs (same as --log-stream off)
149```151```
150 152 
151### Contract-driven commands (automatic)153### Contract-driven commands (automatic)
@@ -184,6 +186,10 @@ the session token for a short-lived platform credential in-process, and injects
184the agent**. gitcode.com and github.com hosts get credentials; on an exchange failure you get a186the agent**. gitcode.com and github.com hosts get credentials; on an exchange failure you get a
185warning and git runs natively. `grape git --help` is identical to `git --help`.187warning and git runs natively. `grape git --help` is identical to `git --help`.
186 188 
189+**Stream boundary:** the passthrough contract covers grape's own logs only — output written by
190+`git` itself, by git hooks or by wrapper scripts is forwarded verbatim and is *not* covered by the
191+`--json-out` stdout guarantee ([details](docs/grape-output-stream-contract.md#5-boundary-grape-git-passthrough-process)).
192+ 
187```bash193```bash
188grape git status # local command (no credential needed)194grape git status # local command (no credential needed)
189grape git clone https://gitcode.com/owner/repo.git # repo parsed from URL → credential injected195grape git clone https://gitcode.com/owner/repo.git # repo parsed from URL → credential injected
@@ -51,7 +51,8 @@ OpenAPI 契约,自动生成 `grape <group> <verb>` 命令,并在本地以进
51- **自动认证注入** — 默认自动携带 Bearer token(客户端同时支持 `PRIVATE-TOKEN` / `?access_token=` 通道)51- **自动认证注入** — 默认自动携带 Bearer token(客户端同时支持 `PRIVATE-TOKEN` / `?access_token=` 通道)
52- **本地 git 透传** — `grape git` 运行真实 git,自动识别仓库,凭据经 `GIT_CONFIG` 注入子进程——不进命令行、不落磁盘52- **本地 git 透传** — `grape git` 运行真实 git,自动识别仓库,凭据经 `GIT_CONFIG` 注入子进程——不进命令行、不落磁盘
53- **内置 `tasks wait`** — 轮询任务直至终态(`completed` / `failed` / `cancelled`)53- **内置 `tasks wait`** — 轮询任务直至终态(`completed` / `failed` / `cancelled`)
54-- **机器可读输出** — `--json-out` 输出单行 JSON,供 worker 与脚本解析54+- **机器可读输出** — `--json-out` 输出单行 JSON,供 worker 与脚本解析;日志/告警只写 **stderr**,
55+ `--json-out | jq` 在告警路径下也不会被打断(见[输出流契约](docs/grape-output-stream-contract.md))
55- **按模式过滤命令** — `GRAPE_CLI_MODE`(WORKER / USER / ALL)按 token 作用域(dual / session-only / user-only)过滤命令集合56- **按模式过滤命令** — `GRAPE_CLI_MODE`(WORKER / USER / ALL)按 token 作用域(dual / session-only / user-only)过滤命令集合
56 57 
57## 安装58## 安装
@@ -142,6 +143,8 @@ grape commands [pattern] # 列出全部契约命令,可管道过滤:gra
142grape refresh # 强制拉取最新 OpenAPI 契约并刷新缓存143grape refresh # 强制拉取最新 OpenAPI 契约并刷新缓存
143grape tasks wait --task-id 56 --timeout 120 --interval 3 # 轮询任务至终态144grape tasks wait --task-id 56 --timeout 120 --interval 3 # 轮询任务至终态
144grape --timeout 300 tasks current # 请求超时上限(默认 30s;git 不受影响)145grape --timeout 300 tasks current # 请求超时上限(默认 30s;git 不受影响)
146+grape --log-stream stderr|stdout|off <cmd> # 日志/告警流向(默认 stderr)
147+grape --quiet <cmd> # 静默日志(等价 --log-stream off)
145```148```
146 149 
147### 契约生成命令(自动)150### 契约生成命令(自动)
@@ -0,0 +1,89 @@
1+# Output stream contract — stdout 只放业务输出,日志只走 stderr
2+ 
3+> 适用版本:grape-cli ≥ 0.3.5(Issue #440)。实现入口:`grape_cli/logs.py`。
4+ 
5+## 1. 一句话契约
6+ 
7+**stdout 只承载命令的业务输出**(`--json-out` 时是且仅是一段 JSON;普通模式是表格/文本结果);
8+**所有日志、提示、告警、降级说明只走 stderr**。因此 stderr 被丢弃(`2>/dev/null`)不影响业务输出,
9+`grape ... --json-out | jq` 在告警路径下同样零报错。
10+ 
11+```bash
12+# 都可直接消费:告警不会打断 jq
13+grape scenes detail --scene_id "$GRAPE_SCENE_ID" --json-out | jq .
14+grape git-repo pulls files --owner o --repo r --number 7 --json-out 2>/dev/null | jq '.files | length'
15+```
16+ 
17+## 2. stdout / stderr 分工
18+ 
19+| 流 | 内容 | 示例 |
20+|----|------|------|
21+| stdout | 业务结果:JSON(`--json-out`,单行)、普通模式的文本/表格、`--raw` 的原始字节、`--dry-run` 预览、`--help` / `grape commands` 列表 | `{"items": [...]}` |
22+| stderr | 日志类:`warning:`(降级/截断/换券失败)、升级提醒、`hint:` 提示、`Error:` 错误 | `warning: page 1 is full (100 results); ...` |
23+ 
24+错误(`Error: ...`)与告警(`warning: ...`)都走 stderr;退出码语义不变(见 README「Exit Codes」)。
25+ 
26+## 3. `--json-out` 契约
27+ 
28+1. stdout 整体是一段可被 `json.loads` / `jq` 解析的 JSON(单行)。
29+2. `--json-out` 下日志**强制**写 stderr:即使同时给了 `--log-stream stdout`,护栏优先——
30+ `--json-out` 的承诺不可被日志开关破坏。
31+3. `--json-out 2>/dev/null` 与 `--json-out` 的业务 JSON 完全一致(stderr 只承载日志)。
32+4. `--dry-run --json-out` 的机器可读预览仍落在 stdout(它本身就是业务输出)。
33+5. `--json-out` 只约束 CLI 自己的输出;`grape git` 透传的外部进程不在其内(见 §5)。
34+ 
35+## 4. 全局开关:`--log-stream` / `--quiet`
36+ 
37+选项挂在根命令上,写在子命令之前:
38+ 
39+| 用法 | 效果 |
40+|------|------|
41+| `grape ... <cmd>`(默认) | 日志写 stderr(与 0.3.x 既有行为一致) |
42+| `grape --log-stream stderr <cmd>` | 同上,显式声明 |
43+| `grape --log-stream stdout <cmd>` | 复现旧行为:日志混入 stdout(**仅非 `--json-out` 生效**) |
44+| `grape --log-stream off <cmd>` | 日志静默(业务输出不受影响) |
45+| `grape --quiet <cmd>` | 等价 `--log-stream off` |
46+| `grape --log-stream console` | 用法错误,退出码 2(可选值只有 `stderr` / `stdout` / `off`) |
47+ 
48+优先级:`--quiet` / `--log-stream off`(静默,什么都不写)> `--json-out` 护栏(强制 stderr)>
49+`--log-stream stdout` > 默认 `stderr`。
50+ 
51+典型用法:
52+ 
53+```bash
54+grape --quiet issues list --owner o --repo r --json-out | jq . # 只要结果,不要提示
55+grape --log-stream stdout git-repo tree --owner o --repo r | ... # 兼容按 stdout 抓日志的老脚本
56+```
57+ 
58+## 5. 边界:`grape git` 透传进程
59+ 
60+`grape git` 是**原生 git 透传**(`subprocess.run(["git", ...], env=...)` 继承 stdio):
61+ 
62+- git 自身、git hook、包装脚本写出的内容(例如某些 hook 的 branch guard `WARNING` 行)
63+ **不属于本契约**,grape 不捕获、不分流、不重格式化——verbatim 透传是透传语义的一部分,
64+ 接管会破坏交互式输出与逐字节可复现性。
65+- grape 自己的告警(换券失败降级)仍走 stderr,且受 `--log-stream` / `--quiet` 控制。
66+- 若需要「git 输出也可脚本消费」,请在调用侧分流:把 `grape git fetch` 的结果按 stdio 分开读,
67+ 或让 hook 自己写 stderr(推荐)。
68+ 
69+## 6. 新增日志点的写法
70+ 
71+```python
72+from grape_cli import logs
73+ 
74+logs.warn("page 1 is full; more pages may exist") # → stderr: warning: page 1 is full; ...
75+logs.notice("grape 0.3.6 is available") # → stderr,无前缀(既有文案不变)
76+logs.emit("info", "...") # 通用出口
77+```
78+ 
79+- 不要再用 `click.echo(..., err=True)` 或直接写 `sys.stderr` 发日志:绕过出口即绕过
80+ `--log-stream` / `--quiet` / `--json-out` 护栏。
81+- `warning` / `error` 级别由出口补一次前缀;文案已带 `warning:` 时不会重复。
82+- 需要「出错并退出」用 `CliError`(`Error:` 走 stderr、非零退出码),不要用 `logs`。
83+ 
84+## 7. 回归测试
85+ 
86+- `test/test_output_stream.py`:出口层(默认 stderr / `off` / `--quiet` / `stdout` / 护栏优先 / 前缀幂等)
87+ 与命令层(分页截断与换券失败的分流、`--json-out` 下 stdout 可解析且单行、丢弃 stderr 结果一致)。
88+- `test/test_git.py`:降级告警的 stdout/stderr 断言显式分离(不再用 `res.output + stderr` 混合判断)。
89+- 任何新告警点若回退到 stdout,上述用例即红。
@@ -0,0 +1,46 @@
1+# Plan — Issue #440 输出流契约实现方案
2+ 
3+## 方案概述
4+ 
5+新增单一日志出口 `grape_cli/logs.py`,由它决定「写哪里 / 写不写」;`--json-out` 通过选项回调置护栏标志,
6+使护栏与日志流向解耦(默认流向不变:stderr)。各告警点从 `click.echo(..., err=True)` / 直接写
7+`sys.stderr` 迁到同一出口,行为逐字保持不变。文档把契约固定成文并要求回归测试守住。
8+ 
9+## 关键设计决策
10+ 
11+| 决策 | 选项 | 选择 | 理由 |
12+|------|------|------|------|
13+| stdout 被污染时的处置 | 硬失败 / 静默改道 stderr | 静默改道 stderr | 契约优先,不打断既有脚本退出码语义 |
14+| 日志出口形态 | 各点各自 `click.echo(err=True)` / 单出口模块 | 单出口模块 | 分散约定已被证明会回退;单出口才能加护栏 |
15+| 护栏触发点 | 每个命令手写判断 / `--json-out` 选项回调 | 选项回调 | 契约命令由 `build_command` 统一生成,挂一处即覆盖全部 `--json-out` 命令 |
16+| `--json-out` + `--log-stream stdout` | 各自生效 / 护栏优先 | 护栏优先(文档写死) | `--json-out` 的承诺是「stdout 只有业务 JSON」,不可被日志开关破坏 |
17+| `grape git` 透传 | 捕获分流 / 文档化边界 | 文档化边界 | verbatim 是透传语义的一部分,接管会破坏 git 交互输出 |
18+| 告警前缀 | 出口统一加 / 消息自带 | 出口补一次 `warning:`/`error:` 前缀,已有前缀不重复 | 新点位不写前缀也合规,旧文案一字不变 |
19+ 
20+## 实现步骤(TDD)
21+ 
22+1. **红**:`test/test_output_stream.py` 先写契约测试——出口层(默认 stderr / off / quiet / stdout /
23+ 护栏优先 / 前缀幂等)与命令层(分页截断 + 换券失败告警分流、`--json-out` 下 stdout 可解析且单行)。
24+2. **绿**:`logs.py` 实现;`cli.py` 注册全局选项并在组回调 `logs.configure(...)`;`registry.py`
25+ `--json-out` 选项挂 `logs.set_json_out`;三处告警点迁移。
26+3. **回归**:`test/test_git.py` 的 `res.output + stderr` 混合断言拆成显式分流断言(stdout 无告警、
27+ stderr 有告警)。
28+4. **文档**:`docs/grape-output-stream-contract.md`,README「Machine-readable output」与 git 段落引用,
29+ CHANGELOG Unreleased 记账。
30+ 
31+## 测试 seam
32+ 
33+- 出口层 seam:`grape_cli.logs` 的 `configure / set_json_out / reset / emit`(模块级状态,`capsys` 断言分流)。
34+- 命令层 seam:`click.testing.CliRunner` 的 `res.stdout` / `res.stderr` 分离(click 8.2+ 语义),
35+ 即以「用户可见的输出流」为断言对象,不测内部函数调用。
36+- 复用既有 seam:分页用例沿用 `build_command` + `fake_httpx`(`test/test_pulls_files_pagination.py` 先例);
37+ git 用例沿用 `git_env` fixture。
38+ 
39+## 风险与缓解
40+ 
41+| 风险 | 缓解 |
42+|------|------|
43+| 全局选项改变参数解析顺序 | 选项挂在根组(`grape --log-stream off <cmd>`),组回调先于子命令选项回调执行,天然完成状态重置 |
44+| 模块级状态在测试间泄漏 | `conftest.py` 的 autouse fixture 与出口层测试各自 `logs.reset()`;`--json-out` 回调传 `bool(value)` 双向复位 |
45+| `update_check` 的 TTY/静默策略被改坏 | 只替换写出函数,保留 `_stderr_isatty()` 与既有开关优先级 |
46+| `grape commands` 等非 `--json-out` 的 stdout 提示被误改 | 护栏只作用于 `--json-out`;迁移只针对已走 stderr 的告警点 |
@@ -0,0 +1,48 @@
1+# Spec — Issue #440 `--json-out` 输出流契约(stdout 仅业务 JSON,日志走 stderr)
2+ 
3+> 来源:Issue #440([转交][user feedback][14093]);开发基线分支 `ldw`;评级 ready。
4+> 前序:VOD(需求收敛)→ Issue Agent(Spec 定稿,comment 203587398)→ Coding(本实现)。
5+ 
6+## 背景
7+ 
8+用户以 `grape ... --json-out | jq` 消费 CLI 输出时被 WARNING 行打断。仓库既有约定「日志走 stderr」
9+已分散落在多个点(`commands/git.py` 换券失败、`registry.py` 分页截断、`update_check.py` 升级提示),
10+但**没有统一出口、没有 `--json-out` 护栏、没有成文契约**,任何新增提示点都可能重新污染 stdout。
11+ 
12+关键事实(已核验):grape-cli 0.3.4 的 `ldw` / `main` 源码中不存在 branch guard 相关告警输出点;
13+报告中的 WARNING 行系经 `grape git` 透传(`subprocess.run` 继承 stdio)显现。故本单交付
14+「CLI 自有告警统一出口 + `--json-out` 护栏 + 文档契约」,透传边界只文档化、不接管。
15+ 
16+## 目标
17+ 
18+1. CLI 自有日志/告警只有一个出口,默认写 stderr(与既有行为一致,不改变默认流向)。
19+2. `--json-out` 模式下 stdout 只有业务 JSON;即使显式 `--log-stream stdout` 也被护栏改道 stderr。
20+3. 提供 `--log-stream stderr|stdout|off` 与 `--quiet`(等价 `off`),可关可开。
21+4. 把契约写成文档并有回归测试守住。
22+ 
23+## 非目标(Out of Scope)
24+ 
25+- `grape git` 透传进程(git 自身 / hook / 包装脚本)的输出捕获与重格式化:verbatim 语义必须保留。
26+- 同族其它缺陷的成因修复:#274(GBK 控制字符)、#243/#211(404 纯文本落 stdout)、#198(组命令裸调用落 help)。
27+ 
28+## 影响模块
29+ 
30+| 模块 | 改动 |
31+|------|------|
32+| `grape_cli/logs.py` | 新增:单一日志出口 + 流向状态 + `--json-out` 护栏 |
33+| `grape_cli/cli.py` | 全局 `--log-stream` / `--quiet` 注册并注入出口状态 |
34+| `grape_cli/registry.py` | `--json-out` 选项挂护栏回调;分页截断告警迁入出口 |
35+| `grape_cli/commands/git.py` | 换券失败告警迁入出口 |
36+| `grape_cli/update_check.py` | 升级提示迁入出口(TTY 判定与静默策略不变) |
37+| `docs/grape-output-stream-contract.md`、`README.md`、`CHANGELOG.md` | 契约文档 + 引用 + 记账 |
38+| `test/test_output_stream.py`、`test/test_git.py` | 新增契约回归测试;拆分混合断言 |
39+ 
40+## 验收标准
41+ 
42+- [ ] `grape ... --json-out` 的 stdout 整体可被 `jq` 解析;无 WARNING/日志行。
43+- [ ] 换券失败、分页截断两条告警路径:告警落 stderr,stdout 纯业务。
44+- [ ] `--json-out 2>/dev/null | jq` 与 `--json-out | jq` 结果一致(丢弃 stderr 不影响业务 JSON)。
45+- [ ] `--quiet` / `--log-stream off` 静默告警,业务 JSON 不受影响;`--log-stream stdout` 复现旧行为。
46+- [ ] 回归测试:`capsys` 断言分流;新增告警点若回退到 stdout 即红。
47+- [ ] 文档标注 stdout/stderr 分工、`--json-out` 契约、`grape git` 透传边界。
48+- [ ] 现有测试全通过(含 `test_cli.py` 的 `grape commands` stdout seam)。
@@ -0,0 +1,17 @@
1+# Task — Issue #440 切片拆解(TDD 红/绿)
2+ 
3+| # | 切片 | 产物 | 提交 |
4+|---|------|------|------|
5+| 1 | 契约先红 | `test/test_output_stream.py`:出口层 6 例(默认 stderr / `--log-stream off` / `--quiet` / `--log-stream stdout` / `--json-out` 护栏优先 / 前缀幂等)+ 命令层 5 例(分页截断分流、`--json-out` stdout 可解析且单行、`--quiet` 静默、`--log-stream stdout` 旧行为、换券失败分流) | `test(#440): ...(先红)` |
6+| 2 | 统一出口 | `grape_cli/logs.py`:`configure / set_json_out / is_json_out / current_stream / emit / reset` | `feat(#440): 新增统一日志出口 ...` |
7+| 3 | 全局开关 | `grape_cli/cli.py`:`--log-stream` / `--quiet` 注册 + 组回调注入状态 | 同上(同一原子变更:出口无开关不可用) |
8+| 4 | 护栏接线 | `grape_cli/registry.py`:`--json-out` 选项回调置护栏;分页截断告警迁入出口 | 同上 |
9+| 5 | 告警点迁移 | `grape_cli/commands/git.py`、`grape_cli/update_check.py` | 同上 |
10+| 6 | 既有断言拆分 | `test/test_git.py`:`res.output + stderr` 混合断言改显式分流 | `test(#440): 混合断言拆分为 stdout/stderr 分流` |
11+| 7 | 文档 + 记账 | `docs/grape-output-stream-contract.md`、`README.md` 引用、`CHANGELOG.md` Unreleased | `docs(#440): 输出流契约文档 ...` |
12+ 
13+## 完成判定
14+ 
15+- `pytest -q`(清空 `GRAPE_CLI_MODE`/`GRAPE_BASE_URL` 等外部注入变量)全绿。
16+- 契约测试在「出口默认流向改回 stdout」或「护栏让位 `--log-stream stdout`」时必红。
17+- `grape git` 透传边界在文档中明确:git 自身及 hook 输出不由本契约保证。
@@ -5,7 +5,7 @@ import time
5 5 
6import click6import click
7 7 
8-from grape_cli import __version__, config, update_check8+from grape_cli import __version__, config, logs, update_check
9from grape_cli.client import ApiClient, CliError9from grape_cli.client import ApiClient, CliError
10from grape_cli.commands.doctor import doctor_command10from grape_cli.commands.doctor import doctor_command
11from grape_cli.commands.git import git_command11from grape_cli.commands.git import git_command
@@ -29,7 +29,8 @@ def wait_command() -> click.Command:
29 @click.option("--task-id", required=True, help="task id")29 @click.option("--task-id", required=True, help="task id")
30 @click.option("--timeout", default=120, help="max wait seconds (default 120)")30 @click.option("--timeout", default=120, help="max wait seconds (default 120)")
31 @click.option("--interval", default=3, help="poll interval seconds (default 3)")31 @click.option("--interval", default=3, help="poll interval seconds (default 3)")
32- @click.option("--json-out", is_flag=True, help="machine-readable JSON output")32+ @click.option("--json-out", is_flag=True, callback=logs.json_out_flag,
33+ help="machine-readable JSON output")
33 def _wait(task_id: str, timeout: int, interval: int, json_out: bool):34 def _wait(task_id: str, timeout: int, interval: int, json_out: bool):
34 api = ApiClient()35 api = ApiClient()
35 _terminal = {"completed", "failed", "cancelled"}36 _terminal = {"completed", "failed", "cancelled"}
@@ -191,9 +192,15 @@ class ContractGroup(click.Group):
191@click.option("--no-proxy", is_flag=True, default=False,192@click.option("--no-proxy", is_flag=True, default=False,
192 help="ignore *_proxy/NO_PROXY environment variables and connect directly "193 help="ignore *_proxy/NO_PROXY environment variables and connect directly "
193 "(same as GRAPE_TRUST_ENV=0)")194 "(same as GRAPE_TRUST_ENV=0)")
195+@click.option("--log-stream", type=click.Choice(list(logs.STREAMS)), default=None,
196+ help="where logs/warnings go: stderr (default) | stdout | off "
197+ "(--json-out always pins them to stderr)")
198+@click.option("--quiet", is_flag=True, default=False,
199+ help="suppress logs/warnings (same as --log-stream off); output unaffected")
194@click.pass_context200@click.pass_context
195def cli(ctx, base_url: str | None, token: str | None, timeout: int | None,201def cli(ctx, base_url: str | None, token: str | None, timeout: int | None,
196- no_proxy: bool, no_version_check: bool = False):202+ no_proxy: bool, no_version_check: bool = False,
203+ log_stream: str | None = None, quiet: bool = False):
197 """Grape CLI: contract-driven commands (new API endpoint -> new command automatically)204 """Grape CLI: contract-driven commands (new API endpoint -> new command automatically)
198 plus local git passthrough (platform token stays in-process).205 plus local git passthrough (platform token stays in-process).
199 206 
@@ -203,10 +210,13 @@ def cli(ctx, base_url: str | None, token: str | None, timeout: int | None,
203 grape --base-url https://grape.example.com --grape-api-token grape_xxx skills list --json-out210 grape --base-url https://grape.example.com --grape-api-token grape_xxx skills list --json-out
204 grape --timeout 120 tasks wait --task-id 56211 grape --timeout 120 tasks wait --task-id 56
205 grape --no-proxy issues list # ignore *_proxy/NO_PROXY env vars212 grape --no-proxy issues list # ignore *_proxy/NO_PROXY env vars
213+ grape --quiet issues list --json-out # silence logs (stdout stays pure JSON)
206 """214 """
207 from grape_cli.config import set_cli_params215 from grape_cli.config import set_cli_params
208 set_cli_params(base_url=base_url or "", token=token or "",216 set_cli_params(base_url=base_url or "", token=token or "",
209 timeout=timeout or 0, no_proxy=no_proxy)217 timeout=timeout or 0, no_proxy=no_proxy)
218+ # Issue #440:统一日志出口的流向开关(默认 stderr;--json-out 护栏由子命令选项回调置位)
219+ logs.configure(stream=log_stream, quiet=quiet)
210 if ctx.invoked_subcommand is None:220 if ctx.invoked_subcommand is None:
211 click.echo(ctx.get_help())221 click.echo(ctx.get_help())
212 return222 return
@@ -16,6 +16,7 @@ from urllib.parse import urlsplit
16 16 
17import click17import click
18 18 
19+from grape_cli import logs
19from grape_cli.client import ApiClient, CliError, basic_auth20from grape_cli.client import ApiClient, CliError, basic_auth
20 21 
21_GITCODE_HOSTS = frozenset({"gitcode.com", "www.gitcode.com"})22_GITCODE_HOSTS = frozenset({"gitcode.com", "www.gitcode.com"})
@@ -118,10 +119,10 @@ def git_command() -> click.Command:
118 try:119 try:
119 _inject_git_credentials(owner_repo, env)120 _inject_git_credentials(owner_repo, env)
120 except CliError as e:121 except CliError as e:
121- click.echo(122+ # Issue #440:降级告警走统一出口(默认 stderr),git 子进程 stdout 不动
122- f"warning: grape git credential injection failed ({e}); "123+ logs.warn(
123- "falling back to native git behavior",124+ f"grape git credential injection failed ({e}); "
124- err=True,125+ "falling back to native git behavior"
125 )126 )
126 127 
127 cmd = ["git"] + args128 cmd = ["git"] + args
@@ -0,0 +1,145 @@
1+"""统一日志/告警出口(Issue #440)。
2+ 
3+契约:CLI 自有的日志、提示、告警一律经本模块写出,**默认写 stderr**,使
4+``grape ... --json-out | jq`` 在告警/降级路径下仍可零报错消费。
5+ 
6+流向:
7+- 默认 ``stderr``(与 0.3.x 既有行为一致,不改变现网脚本的观测);
8+- 全局 ``--log-stream stderr|stdout|off`` 与 ``--quiet``(等价 ``off``)由根命令
9+ 注册后调用 :func:`configure` 落状态;
10+- ``--json-out`` 模式进入 stdout 纯净护栏:日志强制改道 ``stderr``,即使显式
11+ ``--log-stream stdout`` 也护栏优先(``--json-out`` 的承诺不可被日志开关破坏)。
12+ 
13+边界:``grape git`` 透传的 git 进程 / hook / 包装脚本输出不经过本出口
14+(透传语义要求 verbatim),见 ``docs/grape-output-stream-contract.md``。
15+"""
16+from __future__ import annotations
17+ 
18+import sys
19+from typing import TextIO
20+ 
21+STDERR = "stderr"
22+STDOUT = "stdout"
23+OFF = "off"
24+STREAMS = (STDERR, STDOUT, OFF)
25+DEFAULT_STREAM = STDERR
26+ 
27+# 需要自动补前缀的级别:新点位写裸文案即合规,旧文案自带前缀则不重复
28+_PREFIXED = {"warning": "warning", "error": "error"}
29+ 
30+_state = {"stream": DEFAULT_STREAM, "json_out": False}
31+ 
32+ 
33+def reset() -> None:
34+ """复位到默认状态(默认 stderr、无护栏);供测试与进程内复用。"""
35+ _state["stream"] = DEFAULT_STREAM
36+ _state["json_out"] = False
37+ 
38+ 
39+def configure(stream: str | None = None, quiet: bool = False) -> str:
40+ """落地全局开关,返回生效流向。
41+ 
42+ ``quiet``(``--quiet``)优先于 ``stream``,两者等价于 ``off``;
43+ 每次调用同时复位 ``--json-out`` 护栏(一次调用 = 一次进程内命令)。
44+ """
45+ if quiet:
46+ _state["stream"] = OFF
47+ elif stream:
48+ value = str(stream).strip().lower()
49+ if value not in STREAMS:
50+ raise ValueError(f"unknown log stream '{stream}'; expected one of {', '.join(STREAMS)}")
51+ _state["stream"] = value
52+ _state["json_out"] = False
53+ return _state["stream"]
54+ 
55+ 
56+def set_json_out(active: bool = True) -> bool:
57+ """进入/退出 ``--json-out`` stdout 纯净护栏。"""
58+ _state["json_out"] = bool(active)
59+ return _state["json_out"]
60+ 
61+ 
62+def json_out_flag(ctx=None, param=None, value: bool = False) -> bool:
63+ """click 选项回调:``--json-out`` 置/复位护栏(契约命令与内置命令共用一处)。
64+ 
65+ 传 ``bool(value)`` 双向复位,避免同一进程内的模块级状态在命令间串流。
66+ """
67+ set_json_out(value)
68+ return value
69+ 
70+ 
71+def is_json_out() -> bool:
72+ return bool(_state["json_out"])
73+ 
74+ 
75+def current_stream() -> str:
76+ """生效流向:``off`` 静默;``--json-out`` 时强制 ``stderr``;否则按配置。"""
77+ if _state["stream"] == OFF:
78+ return OFF
79+ if _state["json_out"]:
80+ return STDERR
81+ return _state["stream"]
82+ 
83+ 
84+def _format(level: str, message: str) -> str:
85+ text = str(message)
86+ prefix = _PREFIXED.get(str(level).strip().lower())
87+ if prefix and not text.lower().startswith(f"{prefix}:"):
88+ return f"{prefix}: {text}"
89+ return text
90+ 
91+ 
92+def emit(level: str, message: str, *, stream: TextIO | None = None) -> str:
93+ """唯一日志出口:写一条并 flush;被静默时返回空串。
94+ 
95+ ``stream`` 仅用于嵌入方/测试显式指定目标(绕过流向判定),CLI 调用点不传。
96+ """
97+ text = _format(level, message)
98+ if stream is not None:
99+ _write(stream, text)
100+ return text
101+ name = current_stream()
102+ if name == OFF:
103+ return ""
104+ target = sys.stderr if name == STDERR else sys.stdout
105+ if not _write(target, text):
106+ return ""
107+ return text
108+ 
109+ 
110+def _write(stream: TextIO, text: str) -> bool:
111+ """写一行并 flush;任何 IO 异常静默(日志不得影响命令退出码)。"""
112+ try:
113+ stream.write(text + "\n")
114+ stream.flush()
115+ except Exception:
116+ return False
117+ return True
118+ 
119+ 
120+def warn(message: str, *, stream: TextIO | None = None) -> str:
121+ """``emit("warning", ...)`` 的简写。"""
122+ return emit("warning", message, stream=stream)
123+ 
124+ 
125+def notice(message: str, *, stream: TextIO | None = None) -> str:
126+ """``emit("notice", ...)`` 的简写(无前缀,保持既有文案)。"""
127+ return emit("notice", message, stream=stream)
128+ 
129+ 
130+__all__ = [
131+ "DEFAULT_STREAM",
132+ "OFF",
133+ "STDERR",
134+ "STDOUT",
135+ "STREAMS",
136+ "configure",
137+ "current_stream",
138+ "emit",
139+ "is_json_out",
140+ "json_out_flag",
141+ "notice",
142+ "reset",
143+ "set_json_out",
144+ "warn",
145+]
@@ -18,6 +18,7 @@ from importlib.resources import files
18 18 
19import click19import click
20 20 
21+from grape_cli import logs
21from grape_cli.client import ApiClient, CliError, WRITE_METHODS22from grape_cli.client import ApiClient, CliError, WRITE_METHODS
22 23 
23GROUP_ALIAS = {"gitrepo": "git-repo"}24GROUP_ALIAS = {"gitrepo": "git-repo"}
@@ -594,7 +595,11 @@ def build_command(meta: dict) -> click.Command:
594 help="JSON string request body (or @file.json, or - for stdin)"))595 help="JSON string request body (or @file.json, or - for stdin)"))
595 options.append(click.Option(["--json-file"], default=None,596 options.append(click.Option(["--json-file"], default=None,
596 help="read request body JSON from <path> ('-' for stdin)"))597 help="read request body JSON from <path> ('-' for stdin)"))
597- options.append(click.Option(["--json-out"], is_flag=True, help="machine-readable JSON output"))598+ # Issue #440:`--json-out` 即进入 stdout 纯净护栏(日志强制 stderr)。契约命令由
599+ # build_command 统一生成,护栏挂在此选项回调一处即覆盖全部命令(含契约新增端点)。
600+ options.append(click.Option(["--json-out"], is_flag=True,
601+ callback=logs.json_out_flag,
602+ help="machine-readable JSON output"))
598 # Issue #2662:写命令统一注入 --dry-run(method 判定,一处挂全量写命令,603 # Issue #2662:写命令统一注入 --dry-run(method 判定,一处挂全量写命令,
599 # 新增契约写端点自动继承;GET 只读命令不挂)。604 # 新增契约写端点自动继承;GET 只读命令不挂)。
600 if method.upper() in WRITE_METHODS:605 if method.upper() in WRITE_METHODS:
@@ -722,7 +727,8 @@ def build_command(meta: dict) -> click.Command:
722 out, _warn = _run_paginated(api, method, url, params,727 out, _warn = _run_paginated(api, method, url, params,
723 kw.get("page"), kw.get("per_page"))728 kw.get("page"), kw.get("per_page"))
724 if _warn:729 if _warn:
725- click.echo(_warn, err=True)730+ # Issue #440:告警走统一出口(默认 stderr;--json-out 下护栏强制 stderr)
731+ logs.warn(_warn)
726 data = out732 data = out
727 else:733 else:
728 _status, data = api.request(method, url, params=params, json_body=body,734 _status, data = api.request(method, url, params=params, json_body=body,
@@ -24,7 +24,7 @@ import time
24from pathlib import Path24from pathlib import Path
25from typing import Any, TextIO25from typing import Any, TextIO
26 26 
27-from grape_cli import __version__, config27+from grape_cli import __version__, config, logs
28 28 
29RELEASES_LATEST_URL = (29RELEASES_LATEST_URL = (
30 "https://api.gitcode.com/api/v5/repos/grape-dev/grape-cli/releases/latest"30 "https://api.gitcode.com/api/v5/repos/grape-dev/grape-cli/releases/latest"
@@ -313,17 +313,16 @@ def start(*, no_version_check: bool = False, current: str = __version__,
313 313 
314def emit(checker: Checker | None, *, stream: TextIO | None = None,314def emit(checker: Checker | None, *, stream: TextIO | None = None,
315 wait: float = 0.0) -> str | None:315 wait: float = 0.0) -> str | None:
316- """命令结束后调用:取结果并只写 stderr;异常静默。"""316+ """命令结束后调用:取结果并经统一日志出口写出(默认 stderr);异常静默。
317+ 
318+ Issue #440:出口负责流向(`--quiet` / `--log-stream` / `--json-out` 护栏),
319+ 本函数只保留「何时提示」的判定(TTY / 开关 / 一次性 / 版本比较)。
320+ """
317 if checker is None:321 if checker is None:
318 return None322 return None
319 message = checker.finish(wait=wait)323 message = checker.finish(wait=wait)
320 if message:324 if message:
321- out = stream if stream is not None else sys.stderr325+ logs.notice(message, stream=stream)
322- try:
323- out.write(message + "\n")
324- out.flush()
325- except Exception:
326- pass
327 return message326 return message
328 327 
329 328 
@@ -99,15 +99,17 @@ class FakeResponse:
99@pytest.fixture(autouse=True)99@pytest.fixture(autouse=True)
100def _reset_module_state():100def _reset_module_state():
101 """每次用例前重置模块级可变状态,避免用例间串扰。"""101 """每次用例前重置模块级可变状态,避免用例间串扰。"""
102- from grape_cli import config102+ from grape_cli import config, logs
103 from grape_cli import cli103 from grape_cli import cli
104 104 
105 config._CLI_PARAMS = {"base_url": "", "token": "", "timeout": 0, "no_proxy": False}105 config._CLI_PARAMS = {"base_url": "", "token": "", "timeout": 0, "no_proxy": False}
106+ logs.reset() # Issue #440:日志出口状态为模块级,隔离用例间流向
106 cli.cli._loaded = False107 cli.cli._loaded = False
107 cli.cli._groups = {}108 cli.cli._groups = {}
108 cli.cli._load_error = ""109 cli.cli._load_error = ""
109 yield110 yield
110 config._CLI_PARAMS = {"base_url": "", "token": "", "timeout": 0, "no_proxy": False}111 config._CLI_PARAMS = {"base_url": "", "token": "", "timeout": 0, "no_proxy": False}
112+ logs.reset()
111 cli.cli._loaded = False113 cli.cli._loaded = False
112 cli.cli._groups = {}114 cli.cli._groups = {}
113 cli.cli._load_error = ""115 cli.cli._load_error = ""
@@ -232,7 +232,9 @@ def test_git_credential_missing_fields_warns_and_continues(git_env, monkeypatch)
232 res = CliRunner().invoke(cli, ["git", "status"])232 res = CliRunner().invoke(cli, ["git", "status"])
233 assert res.exit_code == 0233 assert res.exit_code == 0
234 assert git_env["cmd"] == ["git", "status"]234 assert git_env["cmd"] == ["git", "status"]
235- assert "git-credential" in (res.output + getattr(res, "stderr", ""))235+ # Issue #440:降级告警只走 stderr,stdout 不得混入日志
236+ assert "git-credential" not in res.stdout
237+ assert "git-credential" in res.stderr
236 238 
237 239 
238def test_git_credentials_unavailable_warns_and_continues(git_env, monkeypatch):240def test_git_credentials_unavailable_warns_and_continues(git_env, monkeypatch):
@@ -244,4 +246,6 @@ def test_git_credentials_unavailable_warns_and_continues(git_env, monkeypatch):
244 monkeypatch.setattr("grape_cli.commands.git._repo_from_cwd", lambda cwd=None: "o/r")246 monkeypatch.setattr("grape_cli.commands.git._repo_from_cwd", lambda cwd=None: "o/r")
245 res = CliRunner().invoke(cli, ["git", "status"])247 res = CliRunner().invoke(cli, ["git", "status"])
246 assert res.exit_code == 0248 assert res.exit_code == 0
247- assert "credential injection failed" in (res.output + getattr(res, "stderr", ""))249+ # Issue #440:降级告警只走 stderr,stdout 不得混入日志
250+ assert "credential injection failed" not in res.stdout
251+ assert "credential injection failed" in res.stderr
@@ -0,0 +1,256 @@
1+"""Issue #440 输出流契约:`--json-out` 下 stdout 仅业务 JSON,日志/告警一律 stderr。
2+ 
3+两层 seam:
4+- 出口层:`grape_cli.logs`(configure / set_json_out / reset / emit)——用 capsys 断言分流;
5+- 命令层:CliRunner 的 `res.stdout` / `res.stderr` 分离——断言用户可见行为(不测内部调用)。
6+ 
7+回归价值:若出口默认流向改回 stdout,或 `--json-out` 护栏让位 `--log-stream stdout`,
8+本文件即红。
9+"""
10+import json
11+from types import SimpleNamespace
12+ 
13+import pytest
14+from click.testing import CliRunner
15+ 
16+from grape_cli.cli import cli
17+from grape_cli.client import CliError
18+from grape_cli.contracts import load_bundled
19+ 
20+FILES_PATH = "/api/git-repo/o/r/pulls/7/files"
21+ 
22+ 
23+@pytest.fixture(autouse=True)
24+def _reset_log_state():
25+ """出口状态是模块级:每个用例前后复位,避免用例间串流。"""
26+ try:
27+ from grape_cli import logs
28+ 
29+ logs.reset()
30+ yield
31+ logs.reset()
32+ except ImportError: # 先红阶段:出口模块尚未实现
33+ yield
34+ 
35+ 
36+# ---------- 出口层:grape_cli.logs ----------
37+ 
38+def test_emit_defaults_to_stderr(capsys):
39+ """默认流向 = stderr(保持既有行为,不改变任何现网脚本的观测)。"""
40+ from grape_cli import logs
41+ 
42+ logs.emit("warning", "boom")
43+ 
44+ captured = capsys.readouterr()
45+ assert captured.out == ""
46+ assert "warning: boom" in captured.err
47+ 
48+ 
49+def test_log_stream_off_silences(capsys):
50+ from grape_cli import logs
51+ 
52+ logs.configure(stream="off")
53+ logs.emit("warning", "boom")
54+ 
55+ captured = capsys.readouterr()
56+ assert captured.out == ""
57+ assert captured.err == ""
58+ 
59+ 
60+def test_quiet_silences(capsys):
61+ """`--quiet` 等价 `--log-stream off`。"""
62+ from grape_cli import logs
63+ 
64+ logs.configure(quiet=True)
65+ assert logs.current_stream() == "off"
66+ logs.emit("warning", "boom")
67+ 
68+ captured = capsys.readouterr()
69+ assert captured.out == ""
70+ assert captured.err == ""
71+ 
72+ 
73+def test_log_stream_stdout_reproduces_legacy_behavior(capsys):
74+ """`--log-stream stdout` 可复现旧行为(告警混在 stdout)。"""
75+ from grape_cli import logs
76+ 
77+ logs.configure(stream="stdout")
78+ logs.emit("warning", "boom")
79+ 
80+ captured = capsys.readouterr()
81+ assert "warning: boom" in captured.out
82+ assert captured.err == ""
83+ 
84+ 
85+def test_json_out_guard_forces_stderr_even_with_log_stream_stdout(capsys):
86+ """护栏优先:`--json-out` 下即使显式 `--log-stream stdout` 也不许污染 stdout。"""
87+ from grape_cli import logs
88+ 
89+ logs.configure(stream="stdout")
90+ logs.set_json_out(True)
91+ logs.emit("warning", "boom")
92+ 
93+ captured = capsys.readouterr()
94+ assert captured.out == ""
95+ assert "warning: boom" in captured.err
96+ 
97+ 
98+def test_emit_does_not_double_prefix(capsys):
99+ """文案自带 `warning:` 时出口不重复加前缀(迁移前后字节一致)。"""
100+ from grape_cli import logs
101+ 
102+ logs.emit("warning", "warning: legacy wording")
103+ logs.emit("warning", "new wording")
104+ 
105+ captured = capsys.readouterr()
106+ assert captured.err == "warning: legacy wording\nwarning: new wording\n"
107+ 
108+ 
109+def test_unknown_stream_rejected():
110+ from grape_cli import logs
111+ 
112+ with pytest.raises(ValueError):
113+ logs.configure(stream="console")
114+ 
115+ 
116+# ---------- 命令层:CLI 端到端 ----------
117+ 
118+def _setup_env(monkeypatch):
119+ monkeypatch.setenv("GRAPE_SESSION_TOKEN", "tk_test")
120+ monkeypatch.setenv("GRAPE_BASE_URL", "http://x")
121+ 
122+ 
123+def _full_page(n: int):
124+ return [{"filename": f"grape_cli/f{i}.py", "additions": 1, "deletions": 0,
125+ "sha": f"s{i}", "patch": "@@ -1 +1 @@"} for i in range(n)]
126+ 
127+ 
128+@pytest.fixture
129+def paged_router(fake_httpx):
130+ """契约 + 满页响应:`--page 1 --per_page 2` 必然触发截断告警。"""
131+ def handler(method, url, kwargs):
132+ from conftest import FakeResponse
133+ 
134+ return FakeResponse(200, _full_page(2))
135+ 
136+ schema = load_bundled()
137+ fake_httpx({"/openapi.json": (200, schema), FILES_PATH: handler})
138+ return {}
139+ 
140+ 
141+def _invoke_paged(args):
142+ return CliRunner().invoke(
143+ cli, ["git-repo", "pulls", "files", "--owner", "o", "--repo", "r",
144+ "--number", "7", "--page", "1", "--per_page", "2"] + args)
145+ 
146+ 
147+def test_json_out_stdout_is_pure_json_on_warning_path(monkeypatch, paged_router):
148+ """验收 1/2:告警路径下 `--json-out` 的 stdout 仍是整体可解析的单段 JSON。"""
149+ _setup_env(monkeypatch)
150+ 
151+ res = _invoke_paged(["--json-out"])
152+ 
153+ assert res.exit_code == 0, res.output
154+ assert res.stdout.count("\n") == 1
155+ data = json.loads(res.stdout)
156+ assert data["_pagination"]["has_more"] is True
157+ assert "warning" not in res.stdout.lower()
158+ assert "more pages may exist" in res.stderr.lower()
159+ 
160+ 
161+def test_json_out_guard_beats_log_stream_stdout(monkeypatch, paged_router):
162+ """护栏优先:`--json-out` + `--log-stream stdout` 时 stdout 依旧纯 JSON。"""
163+ _setup_env(monkeypatch)
164+ 
165+ res = CliRunner().invoke(
166+ cli, ["--log-stream", "stdout", "git-repo", "pulls", "files",
167+ "--owner", "o", "--repo", "r", "--number", "7",
168+ "--page", "1", "--per_page", "2", "--json-out"])
169+ 
170+ assert res.exit_code == 0, res.output
171+ json.loads(res.stdout)
172+ assert "warning" not in res.stdout.lower()
173+ assert "more pages may exist" in res.stderr.lower()
174+ 
175+ 
176+def test_dropping_stderr_keeps_business_json(monkeypatch, paged_router):
177+ """验收 3:`--json-out 2>/dev/null` 与 `--json-out` 的业务 JSON 一致。"""
178+ _setup_env(monkeypatch)
179+ 
180+ with_stderr = _invoke_paged(["--json-out"])
181+ without_stderr = _invoke_paged(["--json-out"])
182+ 
183+ assert with_stderr.stderr # 告警确实存在,否则该用例没有区分力
184+ assert json.loads(with_stderr.stdout) == json.loads(without_stderr.stdout)
185+ 
186+ 
187+def test_log_stream_stdout_restores_legacy_mixed_output(monkeypatch, paged_router):
188+ """验收 4:`--log-stream stdout` 可关可开——旧行为(告警在 stdout)可复现。"""
189+ _setup_env(monkeypatch)
190+ 
191+ res = CliRunner().invoke(
192+ cli, ["--log-stream", "stdout", "git-repo", "pulls", "files",
193+ "--owner", "o", "--repo", "r", "--number", "7",
194+ "--page", "1", "--per_page", "2"])
195+ 
196+ assert res.exit_code == 0, res.output
197+ assert "warning" in res.stdout.lower()
198+ assert "warning" not in res.stderr.lower()
199+ with pytest.raises(json.JSONDecodeError):
200+ json.loads(res.stdout)
201+ 
202+ 
203+def test_quiet_silences_warning_but_keeps_json(monkeypatch, paged_router):
204+ """验收 4:`--quiet` 静默告警,业务 JSON 不受影响。"""
205+ _setup_env(monkeypatch)
206+ 
207+ res = CliRunner().invoke(
208+ cli, ["--quiet", "git-repo", "pulls", "files", "--owner", "o", "--repo", "r",
209+ "--number", "7", "--page", "1", "--per_page", "2", "--json-out"])
210+ 
211+ assert res.exit_code == 0, res.output
212+ assert "warning" not in res.stderr.lower()
213+ assert json.loads(res.stdout)["_pagination"]["page"] == 1
214+ 
215+ 
216+def test_invalid_log_stream_exits_with_usage_error(monkeypatch):
217+ _setup_env(monkeypatch)
218+ 
219+ res = CliRunner().invoke(cli, ["--log-stream", "console", "git", "status"])
220+ 
221+ assert res.exit_code == 2
222+ 
223+ 
224+def _broken_credential_env(monkeypatch):
225+ class _DownApi:
226+ def request(self, method, path):
227+ raise CliError("HTTP 403: Forbidden", code=403)
228+ 
229+ monkeypatch.setattr("grape_cli.commands.git.shutil.which", lambda _: "git")
230+ monkeypatch.setattr("grape_cli.commands.git.subprocess.run",
231+ lambda *a, **kw: SimpleNamespace(returncode=0))
232+ monkeypatch.setattr("grape_cli.commands.git.ApiClient", lambda *a, **k: _DownApi())
233+ monkeypatch.setattr("grape_cli.commands.git._repo_from_cwd", lambda cwd=None: "o/r")
234+ 
235+ 
236+def test_git_credential_warning_goes_to_stderr(monkeypatch):
237+ """验收 2:换券失败告警落 stderr,stdout 无告警文本。"""
238+ _setup_env(monkeypatch)
239+ _broken_credential_env(monkeypatch)
240+ 
241+ res = CliRunner().invoke(cli, ["git", "status"])
242+ 
243+ assert res.exit_code == 0, res.output
244+ assert "credential injection failed" not in res.stdout
245+ assert "credential injection failed" in res.stderr
246+ 
247+ 
248+def test_quiet_silences_git_credential_warning(monkeypatch):
249+ _setup_env(monkeypatch)
250+ _broken_credential_env(monkeypatch)
251+ 
252+ res = CliRunner().invoke(cli, ["--quiet", "git", "status"])
253+ 
254+ assert res.exit_code == 0, res.output
255+ assert "credential injection failed" not in res.stdout
256+ assert "credential injection failed" not in res.stderr