Skip to content

feat(cli): add --json to remaining commands with a stable error contract - #152

Merged
codeasier merged 5 commits into
mainfrom
feat/issue-138-cli-json
Sep 19, 2026
Merged

codeasier merged 5 commits into
mainfrom
feat/issue-138-cli-json

Conversation

@codeasier

Copy link
Copy Markdown
Owner

Summary

  • Add --json to focus, import, split, query, and config, with a shared Path/dataclass serializer and a success envelope (schema_version, ok, plus db_path / focus_source / device_id / template / effective_params where they apply).
  • JSON failures write {ok: false, error: {code, message, hint}} to stderr, leave stdout empty, and exit nonzero. Stable codes include TEMPLATE_NOT_FOUND, INVALID_PARAMETER, DATABASE_NOT_FOUND, and DEVICE_NOT_FOUND.
  • Keep text-mode Error: on stdout. Leave existing metadata --json and report peak-memory --json success fields unwrapped. split --json is independent of --format json; focus --session --json reports validation and env assignment without implying the parent shell changed.

Test plan

  • pytest (945 passed, 1 xfailed)
  • ruff check . and black --check .
  • basedpyright (0 errors)
  • Confirm JSON success/error paths on focus, import, split, query, and config
  • Confirm query --template-info --json includes feat(query): expose field units and interpretation limits on templates #147 field semantics
  • Confirm metadata --json / report peak-memory --json success fields are unchanged

Related Issue

Fixes #138

Snapshot Runtime Provenance

  • Snapshot provenance evaluation completed when snapshot runtime files change
    Snapshot provenance decision: no-update
    Snapshot provenance no-update reason: This PR only changes CLI JSON output, core helpers, tests, docs, and the helper skill. It does not modify src/pt_snap_cli/snapshot/**.

Agents need parseable success and failure on focus, import, split, query,
and config. JSON failures write structured codes to stderr with empty
stdout; text mode keeps Error: on stdout.

@codeasier codeasier left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

交叉评审结论(Cross-Review)

由 3 个独立模型(qwen3.8-flash / deepseek-v4.1-flash / muse-spark-1.3-contributor)并行评审、父会话逐条核实后的结论:Approve with nits。

核心 JSON 契约实现正确:成功信封、stderr 错误对象与稳定错误码、失败时非零退出且 stdout 为空、文本模式输出保持不变、metadata / report 成功载荷未改动——均已验证。无高/中严重度问题;以下行内评论均为低严重度或信息级(加固、文档准确性、测试缺口),不阻塞合并。

Comment thread README.md Resolved
Comment thread README_zh.md Resolved
Comment thread CHANGELOG.md Resolved
Comment thread src/pt_snap_cli/cli.py Resolved
Comment thread src/pt_snap_cli/cli.py Resolved
Comment thread src/pt_snap_cli/cli.py Resolved
Comment thread src/pt_snap_cli/core/json_codec.py Resolved
Comment thread tests/test_cli_json.py Resolved
Comment thread src/pt_snap_cli/cli.py Resolved
Comment thread src/pt_snap_cli/cli.py Resolved
Typer 0.27 vendors Click, so click.get_current_context() never saw
--json and CI wrote text Error: lines to stdout.
@codeasier

Copy link
Copy Markdown
Owner Author

Follow-up

Pushed 284394a to fix CI and address the cross-review nits.

CI root cause: Typer 0.27 vendors Click as typer._click, so click.get_current_context() never saw --json and JSON failures wrote text Error: to stdout. JSON mode is now a ContextVar set by the --json callback.

Review threads are replied and resolved. Deferred: exposing resolved focus on QueryResult, and replacing the InvalidDeviceError string branch with a subtype.

@codeasier codeasier left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

跟进交叉评审(第二轮,head 284394a)

由 3 个独立模型(qwen3.8-flash / deepseek-v4.1-flash / muse-spark-1.3-contributor)对修复提交重新评审、父会话逐条核实。

结论:Approve with nits。 上一轮 8 项意见妥善解决 6 项;本轮新增 1 项中等发现(用法错误绕过错误信封)与若干低严重度问题,详见行内评论。

上一轮意见落实情况

上轮发现 状态
README 夸大 skill --json ✅ 已修复
CHANGELOG 未记录 skill 错误信封变更 ✅ 已修复
query --json 成功后重复解析 focus ❌ 未处理(见行内评论)
focus --session/--global --json 无 db 歧义 ✅ 已文档化 + 测试
_effective_query_params 未捕获异常 ⚠️ 改为静默吞掉,引入新问题(见行内评论)
to_jsonable 遇 bytes 硬失败 ✅ 已修复(utf-8/replace + memoryview + 测试)
测试缺口 ✅ 大部分已补;import --json 错误路径仍缺(见行内评论)
硬编码错误码 / 字符串匹配 硬编码 ✅;字符串匹配 ❌ 未处理(见行内评论)

_JSON_MODE ContextVar 机制(应对 Typer 0.27 vendor Click)经三方验证正确:main() 回调先重置、11 个命令全部改用 _json_flag()、无跨调用泄漏。

建议合并前优先处理 A(用法错误绕过信封) 与 B(effective_params.limit 不反映 -n 截断),其余可后续跟进。

Comment thread docs/en/querying.md Resolved
Comment thread skills/pt-snap-helper/SKILL.md Resolved
Comment thread src/pt_snap_cli/cli.py Resolved
Comment thread src/pt_snap_cli/cli.py Resolved
Comment thread src/pt_snap_cli/cli.py Resolved
Comment thread docs/en/focus-management.md Resolved
Comment thread docs/en/database.md Resolved
Comment thread tests/test_cli_json.py Resolved
Comment thread src/pt_snap_cli/core/json_codec.py Resolved
Comment thread src/pt_snap_cli/cli.py Resolved
codeasier added 2 commits September 19, 2026 13:49
Agents hitting Click parse failures still need the error envelope, and
effective_params must show the limit that actually ran.
top_n templates already cap SQL before -n is injected, and non-standalone
Abort/Ctrl-C dropped both the text prompt and the error envelope.

@codeasier codeasier left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

第四轮交叉评审(head e6521d2)— 请求修改(Request Changes;因本 PR 为本人提交,无法使用 REQUEST_CHANGES 事件,以下结论同等有效)

由 3 个独立模型(qwen3.8-flash / deepseek-v4.1-flash / muse-spark-1.3-contributor)评审、父会话逐条核实并实证。

本轮请求修改的原因:

  1. [高·阻断,连续第二轮未修复] _safe_call 丢弃 Click/Typer 非 standalone 模式返回的退出码——经 pt-snap 入口的所有领域错误(JSON 与文本模式)退出码为 0,直接违反「失败退出码非零」的核心契约。已实测:pt-snap query --template-info does_not_exist --json 信封正确但 exit 0。
  2. [高·同根因] 真实 Ctrl-C(Exit(130))被 Typer _main 捕获返回,except Exit + _emit_aborted() 分支在真实运行中不可达——Ctrl-C 实际 exit 0、无任何输出。新增测试直接 patch app,只测到了死分支。
  3. [中·本提交的新修复有误] reported_sql_limit 对 active_memory_callstack_at_event 上报 min(top_n, -n),但该模板的 LIMIT {{ top_n }} 在 CTE 内部、外层查询无 trailing LIMIT,_apply_limit 实际追加 LIMIT -n。已渲染实际 SQL 实证:-n 50 时 SQL 为 LIMIT 50、信封却报 limit: 20,returned 可为 21–50 行。

修复方向(1/2 同解,一行):

rv = app(standalone_mode=False)
if rv == 130:
    _emit_aborted()
return rv if isinstance(rv, int) else 0

并补一个真实 argv 穿过 _safe_call 的失败用例(JSON 与文本模式各一)——现有套件全部经 CliRunner(standalone 语义),这正是该回归连续漏网的原因。

上轮意见落实: 退出码/Ctrl-C ❌ 未修复;top_n limit ⚠️ 修错方向(见上);argv 检测 ⚠️ 精致化但仍有 --opt=value 与负数值两个漏检边界(见行内评论)。

修复以上三项后应该可以合并;其余为低/信息级,见行内评论。

Comment thread src/pt_snap_cli/cli.py Resolved
Comment thread src/pt_snap_cli/cli.py Resolved
Comment thread src/pt_snap_cli/query/executor.py Resolved
Comment thread tests/test_cli_json.py Resolved
Comment thread tests/test_cli_json.py Resolved
Comment thread src/pt_snap_cli/cli.py Resolved
Comment thread src/pt_snap_cli/cli.py Resolved
Non-standalone Typer returns Exit codes instead of raising, so domain
failures must propagate that value. Inner top_n is not a trailing LIMIT.

@codeasier codeasier left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

第五轮交叉评审(head c28231d)— ✅ 建议合入

由 3 个独立模型(qwen3.8-flash / deepseek-v4.1-flash / muse-spark-1.3-contributor)评审、父会话逐条核实并实证。(因本 PR 为本人提交,GitHub 不允许 APPROVE 事件,以下结论同等有效。)

上一轮三项请求修改全部修复,经三方独立确认 + 实证:

  1. 退出码 ✅:_safe_call 使用 app(standalone_mode=False) 返回值;实测域错误 JSON/文本均 exit 1、用法错误 exit 2、_safe_call 返回 1;rv==130 走共享 _emit_aborted()。
  2. Ctrl-C ✅:130 检查移至 try 块后,测试改为 return_value=130。
  3. reported_sql_limit ✅:只返回注入值,top_n 独立保留;实测 -n 50→limit: 50、top_n: 20;全模板 grep 确认 trailing LIMIT 均为 {{ limit }}、top_n 全在 CTE 内。
  4. 测试固化 ✅:现渲染真实 SQL 提取 trailing LIMIT 对比。
  5. argv 检测 ✅:--opt=value 与数字 token 不再吞 --json。

事实更正:上轮回复中「except-Exit 分支已移除」与实际不符——分支保留在 cli.py:1418-1419。保留是合理的:pyproject.toml 钉 typer>=0.9.0,旧版 Click main 会 re-raise Exit,该分支是必要安全网;两路径收敛到共享 130 检查,无双重处理。

回归扫描:9 文件 diff 无回归(docs 中英对齐、skills 与 bundled 副本同 blob、CHANGELOG 准确、文本模式逐字保留)。延后项(重复 resolve_focus、no-device 字符串匹配、report metric hint)仍可接受。

剩余发现均不阻断:1 低(dash 值边界,见行内评论)+ 3 信息 + 1 Nit。可作为后续 follow-up,不阻塞合入。

Comment thread src/pt_snap_cli/cli.py
try:
_ = float(token)
except ValueError:
return token.startswith("-")

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

[低·已实证] dash 前缀值导致 JSON 信封漏检,与 = 形式行为不一致

pt-snap report peak-memory <db> --metric -x --json(空格分隔)→ 纯文本用法错误、exit 2;而 --metric=-x --json(= 形式)→ 正确的 INVALID_PARAMETER 信封。两者仅语法糖之差却行为不同,与文档「用法错误也写信封」的平铺承诺矛盾。

机制:-x 以 - 开头且非数字 → 这行把它判为「取值选项」→ 真实的 --json flag 被当作其值 → 漏检。同时 Click 的 BadParameter(Choice 校验)在回调前抛出,ContextVar 也未设置,两个检测路径同时失效。

同类:--device -x --json、未知选项 --bogus --json。建议:两 token 回溯(dash token 的前一个 token 是已知取值选项时视为值),或仅匹配已知取值选项名而非 startswith("-");至少补测试钉住该降级行为(现有用例只覆盖 -n -1 与 = 形式)。不阻塞合入。

Comment thread src/pt_snap_cli/cli.py

# Flag-only options used when a parse failure happens before the --json callback.
# A following --json is treated as a value of the previous option otherwise.
_FLAG_ONLY_OPTIONS = frozenset(

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

[信息] _FLAG_ONLY_OPTIONS 手工清单无漂移防护

当前清单完整(对全部 is_flag/flag-pair 选项核对过),但未来新增布尔 flag 忘记登记会静默漏扫(fails closed 到文本模式,不崩溃)。建议一个内省测试:遍历 app 注册的 Click 参数,断言每个 is_flag 长名都在集合内。

return min(existing_limit, injected)


def reported_sql_limit(

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

[信息] reported_sql_limit 的正确性依赖未钉住的模板不变量

「reported == 实际 trailing LIMIT」仅当没有模板以外层非 limit 参数的 LIMIT 结尾时成立(当前全部模板满足:trailing 全是 {{ limit }},top_n 都在 CTE 内)。未来违反该不变量的模板会无声复现第四轮的 effective_params.limit 错位。建议 registry 级参数化测试:对每个模板渲染(小 -n)并断言 trailing LIMIT == reported_sql_limit。

``parameters`` is the template parameter map so callers can pass it
without a second helper; the merge itself reads ``validated``.
"""
_ = parameters

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

[Nit] parameters 形参已死

_ = parameters 仅为兼容上一迭代的调用签名保留,docstring 已如实说明。后续清理时可连同调用点的关键字参数一起移除。

Comment thread tests/test_cli_json.py
assert "hint" in payload["error"]


def test_safe_call_json_sigint_uses_returned_exit_code(

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

[信息] 真实 Ctrl-C 仅 mock 验证

130 路径现经 return_value=130 测试,但 typer ≥0.27 vendor 了 Click(Abort 是 RuntimeError 子类,非 ClickException),真实 SIGINT 下 vendored Abort 是否被 except (Abort, ClickAbort) 捕获无法从仓库证据判定。一个 subprocess SIGINT 集成测试即可封住该残余缺口。

@codeasier
codeasier merged commit 3f39746 into main Sep 19, 2026
6 checks passed
@codeasier
codeasier deleted the feat/issue-138-cli-json branch October 3, 2026 19:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[FEATURE] 为 pt-snap 所有命令增加 --json 选项,实现 Agent 友好输出

1 participant