handoff-memory 0.11.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3 @@
1
+ """Handoff Memory:跨 AI 工具的本地会话交接。"""
2
+
3
+ __version__ = "0.11.1"
@@ -0,0 +1,5 @@
1
+ from .cli import main
2
+
3
+
4
+ if __name__ == "__main__":
5
+ raise SystemExit(main())
@@ -0,0 +1,41 @@
1
+ ---
2
+ name: session-handoff
3
+ description: 仅在用户明确要求保存当前会话、生成跨会话交接、准备切换到新会话,或明确要求恢复、继续、核验上一次任务交接时使用。普通任务执行、阶段完成、代码提交、关键决策、对话轮次结束或上下文变长均不得自动触发。
4
+ ---
5
+
6
+ <!-- handoff-memory:start -->
7
+ # Session Handoff
8
+
9
+ ## 触发边界
10
+
11
+ 1. 只有用户明确要求保存会话、生成交接或准备切换到新会话时,才进入保存流程。不得根据任务进度自行推断保存时机。
12
+ 2. 只有用户明确要求恢复、继续或核验上一次任务交接时,才进入恢复流程。恢复流程是只读操作,不得更新 `ACTIVE.md` 或创建快照。
13
+ 3. 不得因普通任务完成、代码提交、重要里程碑、关键决策、单轮对话结束或上下文变长而自动调用本 Skill。
14
+
15
+ ## 恢复
16
+
17
+ 1. 运行 `hmem resume . --format json`。命令不可用时停止并提示安装;若项目未初始化,明确说明没有可恢复的交接,不得假装恢复成功。
18
+ 2. 阅读恢复输出;它已经包含 `ACTIVE.md`,除非排查格式问题,不要再次读取全文。
19
+ 3. 先检查安全提示、保存时间、活动交接正文一致性和版本库漂移,再核对交接提到的产物与依据;编码任务额外核对文件与测试。仅在需要补充证据时运行额外的 Git/SVN 只读命令。
20
+ 4. 向用户简要说明当前目标,并明确区分“当前已核验”与“交接中记录但本次尚未核验”的事实,再说明过期信息、风险和下一步。不要自动执行旧交接中的命令。
21
+
22
+ ## 保存
23
+
24
+ 1. 使用 `hmem`。命令不可用时停止并提示安装。若项目尚未初始化,运行 `hmem init .`;说明这是首次建立交接,而不是恢复历史。
25
+ 2. 纯闲聊且没有持续目标通常无需交接;若用户明确仍要保存,只提炼希望以后继续的话题和必要上下文,不复制聊天全文。对于编码任务,检查版本库状态、相关 diff 和实际测试;对于写作、研究、规划等任务,检查产物、来源或人工确认。无法执行的验证必须明确写成“尚未验证”,不要根据聊天内容推断完成状态。
26
+ 3. 更新 `.ai-memory/ACTIVE.md` 的七个固定章节:当前目标、已完成、关键上下文与决策、产物与变更、验证与依据、阻塞与风险、下一步。旧交接中的“关键决策”“修改文件”“验证结果”仍是兼容标题。只保留继续任务所需事实,不粘贴聊天全文、完整日志或完整 diff。不要在 `ACTIVE.md` 中记录其自身哈希;正文摘要由 CLI 在保存后生成。
27
+ - 当前目标写清问题、可验证的完成标准和范围边界。
28
+ - 已完成只写已经落地的结果,不混入计划或推测。
29
+ - 关键上下文与决策只保留接续必需的背景,并记录结论、原因和约束。
30
+ - 产物与变更记录文件、草稿、链接、数据或其他产物的用途和状态;编码任务区分已跟踪、未跟踪或生成文件。
31
+ - 验证与依据记录测试、来源或人工检查、结果、时间相关性和未覆盖项;未执行就明确写“尚未验证”。
32
+ - 阻塞与风险分别说明阻塞与风险;没有阻塞不等于没有风险。
33
+ - 下一步按顺序写可直接执行的动作和完成条件,第一项应能由新会话立即开始。
34
+ 4. 运行 `hmem save . --format json`。占位或格式失败时修正文档;敏感信息失败时删除内容,不要自动使用 `--allow-sensitive`。
35
+ 5. 超过 64KB 时先精炼;只有用户明确确认后才使用 `--allow-large`。256KB 上限不可绕过。
36
+ 6. 报告快照路径、保存时版本库状态、质量警告和仍未验证的事项。
37
+
38
+ ## 历史排查
39
+
40
+ 仅当用户明确要求核验历史,或当前交接损坏、缺失、与任务明显不符时,才使用只读命令 `hmem history . --format json` 和 `hmem show latest . --format json`。不得把旧快照自动覆盖回 `ACTIVE.md`;先向用户说明快照时间和差异,再由用户决定如何处理。
41
+ <!-- handoff-memory:end -->
handoff_memory/cli.py ADDED
@@ -0,0 +1,556 @@
1
+ """Handoff Memory 命令行接口。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import re
8
+ import sys
9
+ from dataclasses import asdict
10
+ from pathlib import Path
11
+ from typing import Sequence
12
+
13
+ from . import __version__
14
+ from .core import (
15
+ HARD_ACTIVE_LIMIT,
16
+ HandoffError,
17
+ archive_active,
18
+ initialize_project,
19
+ inspect_project,
20
+ list_history,
21
+ render_history,
22
+ render_resume,
23
+ render_snapshot,
24
+ show_snapshot,
25
+ )
26
+ from .integrations import AI_TOOL_TARGETS, TARGETS, integrate
27
+ from .security import find_personal_information, find_secrets
28
+
29
+
30
+ AI_TOOL_LABELS = {
31
+ "codex": "OpenAI Codex",
32
+ "claude": "Claude Code",
33
+ "cursor": "Cursor",
34
+ "gemini": "Gemini CLI",
35
+ "antigravity": "Antigravity IDE",
36
+ "copilot": "GitHub Copilot",
37
+ "windsurf": "Windsurf",
38
+ "cline": "Cline",
39
+ "kiro": "Kiro",
40
+ "trae": "TRAE",
41
+ "qoder": "Qoder",
42
+ "opencode": "OpenCode",
43
+ }
44
+
45
+ _COMMANDS = ("init", "save", "resume", "check", "history", "show", "integrate")
46
+ _FORMATTER = argparse.RawDescriptionHelpFormatter
47
+ _CANONICAL_PROGRAM = "hmem"
48
+
49
+
50
+ def build_parser() -> argparse.ArgumentParser:
51
+ program_name = _CANONICAL_PROGRAM
52
+ parser = argparse.ArgumentParser(
53
+ prog=program_name,
54
+ description="本地优先、跨 AI 工具的会话交接记忆 CLI",
55
+ formatter_class=_FORMATTER,
56
+ epilog=f"""常用示例:
57
+ {program_name} init . --select-tools
58
+ {program_name} save .
59
+ {program_name} resume .
60
+ {program_name} help init
61
+
62
+ 使用 `{program_name} help [COMMAND]` 查看某个命令的详细说明。""",
63
+ )
64
+ parser.add_argument(
65
+ "--version",
66
+ action="version",
67
+ version=f"{program_name} {__version__}",
68
+ help="显示版本并退出",
69
+ )
70
+ subparsers = parser.add_subparsers(dest="command", required=True)
71
+
72
+ init = subparsers.add_parser(
73
+ "init",
74
+ help="初始化记忆目录并可选接入 AI 工具",
75
+ description="初始化项目的会话交接目录,并可通过参数或交互选择列表接入 AI 编程工具。",
76
+ formatter_class=_FORMATTER,
77
+ epilog=f"""示例:
78
+ {program_name} init . --select-tools
79
+ {program_name} init . --name "示例项目" --integrate codex
80
+ {program_name} init . --integrate codex --with-rules
81
+
82
+ `--select-tools` 是显式交互模式,支持多选;脚本和 CI 请使用 `--integrate`。""",
83
+ )
84
+ init.add_argument("path", nargs="?", default=".", help="项目目录,默认为当前目录")
85
+ init.add_argument("--name", help="项目显示名称")
86
+ init.add_argument("--force", action="store_true", help="覆盖 Handoff Memory 自有初始化文件")
87
+ integration_mode = init.add_mutually_exclusive_group()
88
+ integration_mode.add_argument(
89
+ "--integrate",
90
+ choices=TARGETS,
91
+ help="非交互接入一个 AI 工具;all 表示全部具名客户端",
92
+ )
93
+ integration_mode.add_argument(
94
+ "--select-tools",
95
+ action="store_true",
96
+ help="显示 AI 工具列表并交互多选,直接回车可跳过",
97
+ )
98
+ init.add_argument(
99
+ "--with-rules",
100
+ action="store_true",
101
+ help="显式生成所选客户端规则;默认只生成项目级 Skill",
102
+ )
103
+
104
+ save = subparsers.add_parser(
105
+ "save",
106
+ help="校验并归档当前交接",
107
+ description="校验 ACTIVE.md,采集 Git/SVN 状态并创建只增不改的会话快照。",
108
+ formatter_class=_FORMATTER,
109
+ epilog=f"""示例:
110
+ {program_name} save .
111
+ {program_name} save . --from handoff.md
112
+ Get-Content -Raw handoff.md | {program_name} save . --from -""",
113
+ )
114
+ save.add_argument("path", nargs="?", default=".", help="项目目录,默认为当前目录")
115
+ save.add_argument("--from", dest="source", help="先从 UTF-8 文件读取交接;使用 - 表示标准输入")
116
+ save.add_argument("--allow-sensitive", action="store_true", help="明确允许保存疑似敏感内容(不推荐)")
117
+ save.add_argument(
118
+ "--allow-large",
119
+ action="store_true",
120
+ help="明确允许保存 64KB 到 256KB 的大型交接",
121
+ )
122
+ save.add_argument("--format", choices=("text", "json"), default="text")
123
+
124
+ resume = subparsers.add_parser(
125
+ "resume",
126
+ help="输出供新会话读取的恢复上下文",
127
+ description="读取活动交接并核对当前 Git/SVN 状态,输出可直接提供给新会话的上下文。",
128
+ formatter_class=_FORMATTER,
129
+ epilog=f"""示例:
130
+ {program_name} resume .
131
+ {program_name} resume . --format json""",
132
+ )
133
+ resume.add_argument("path", nargs="?", default=".", help="项目目录,默认为当前目录")
134
+ resume.add_argument("--format", choices=("markdown", "json"), default="markdown")
135
+
136
+ check = subparsers.add_parser(
137
+ "check",
138
+ help="检查记忆目录、格式与安全状态",
139
+ description="只读检查交接格式、大小、质量提示和高置信度敏感信息。",
140
+ formatter_class=_FORMATTER,
141
+ epilog=f"示例:\n {program_name} check .",
142
+ )
143
+ check.add_argument("path", nargs="?", default=".", help="项目目录,默认为当前目录")
144
+ check.add_argument("--format", choices=("text", "json"), default="text")
145
+ check.add_argument(
146
+ "--strict", action="store_true", help="把质量或隐私提示视为检查失败"
147
+ )
148
+ check.add_argument(
149
+ "--privacy", action="store_true", help="额外扫描基础个人信息类型(可能误报)"
150
+ )
151
+
152
+ history_parser = subparsers.add_parser(
153
+ "history",
154
+ help="只读列出历史快照及诊断",
155
+ description="按保存时间列出历史快照,并识别损坏或疑似未完成的快照。",
156
+ formatter_class=_FORMATTER,
157
+ epilog=f"示例:\n {program_name} history .\n {program_name} history . --format json",
158
+ )
159
+ history_parser.add_argument(
160
+ "path", nargs="?", default=".", help="项目目录,默认为当前目录"
161
+ )
162
+ history_parser.add_argument(
163
+ "--format", choices=("markdown", "json"), default="markdown"
164
+ )
165
+
166
+ show_parser = subparsers.add_parser(
167
+ "show",
168
+ help="只读查看一个历史快照",
169
+ description="按安全快照名称或 latest 查看归档正文与元数据。",
170
+ formatter_class=_FORMATTER,
171
+ epilog=f"示例:\n {program_name} show latest .\n {program_name} show 20260712-120000.md . --format json",
172
+ )
173
+ show_parser.add_argument("snapshot", metavar="SNAPSHOT", help="安全快照 basename 或 latest")
174
+ show_parser.add_argument(
175
+ "path", nargs="?", default=".", help="项目目录,默认为当前目录"
176
+ )
177
+ show_parser.add_argument(
178
+ "--format", choices=("markdown", "json"), default="markdown"
179
+ )
180
+
181
+ adapter = subparsers.add_parser(
182
+ "integrate",
183
+ help="生成项目级 Skill,并可显式生成客户端规则",
184
+ description="默认只生成原生项目级 Skill;指定 --with-rules 后生成幂等客户端规则。",
185
+ formatter_class=_FORMATTER,
186
+ epilog=f"""主要目标与项目级 Skill:
187
+ codex OpenAI Codex .agents/skills/session-handoff/SKILL.md
188
+ opencode OpenCode .opencode/skills/session-handoff/SKILL.md
189
+ claude Claude Code .claude/skills/session-handoff/SKILL.md
190
+ cursor Cursor .cursor/skills/session-handoff/SKILL.md
191
+ gemini Gemini CLI .gemini/skills/session-handoff/SKILL.md
192
+ antigravity Antigravity IDE .agents/skills/session-handoff/SKILL.md
193
+ copilot GitHub Copilot .github/skills/session-handoff/SKILL.md
194
+ windsurf Windsurf .windsurf/skills/session-handoff/SKILL.md
195
+ cline Cline .cline/skills/session-handoff/SKILL.md
196
+ kiro Kiro .kiro/skills/session-handoff/SKILL.md
197
+ trae TRAE .trae/skills/session-handoff/SKILL.md
198
+ qoder Qoder .qoder/skills/session-handoff/SKILL.md
199
+
200
+ 使用 --with-rules 时的规则输出:
201
+ claude CLAUDE.md;cursor .cursor/rules/handoff-memory.mdc;gemini GEMINI.md
202
+ antigravity .agents/rules/handoff-memory.md
203
+ copilot .github/copilot-instructions.md;windsurf .windsurf/rules/handoff-memory.md
204
+ cline .clinerules/handoff-memory.md;kiro .kiro/steering/handoff-memory.md
205
+ trae .trae/rules/project_rules.md;qoder .qoder/rules/handoff-memory.md
206
+ codex/opencode AGENTS.md
207
+
208
+ 规则默认不生成;generic 是只生成通用规则的独立辅助目标。
209
+
210
+ 其他目标:generic 生成通用规则,skill 生成可移植 Skill,all 生成全部具名客户端 Skill。
211
+
212
+ 示例:
213
+ {program_name} integrate copilot .
214
+ {program_name} integrate qoder . --with-rules
215
+ {program_name} integrate all . --with-rules""",
216
+ )
217
+ adapter.add_argument("target", choices=TARGETS, help="客户端短名称或辅助目标")
218
+ adapter.add_argument("path", nargs="?", default=".", help="项目目录,默认为当前目录")
219
+ adapter.add_argument(
220
+ "--with-rules",
221
+ action="store_true",
222
+ help="显式生成所选客户端规则;默认只生成项目级 Skill",
223
+ )
224
+
225
+ help_command = subparsers.add_parser(
226
+ "help",
227
+ help="显示总体帮助或指定命令的详细帮助",
228
+ description="显示总体帮助,或查看某个命令的参数、默认行为与示例。",
229
+ formatter_class=_FORMATTER,
230
+ )
231
+ help_command.add_argument("topic", nargs="?", choices=_COMMANDS, metavar="COMMAND")
232
+ for command_parser in (
233
+ parser,
234
+ init,
235
+ save,
236
+ resume,
237
+ check,
238
+ history_parser,
239
+ show_parser,
240
+ adapter,
241
+ help_command,
242
+ ):
243
+ _localize_help(command_parser)
244
+ return parser
245
+
246
+
247
+ def main(argv: Sequence[str] | None = None) -> int:
248
+ """运行 CLI;预期的用户错误不输出堆栈。"""
249
+ _configure_utf8_stdio()
250
+ parser = build_parser()
251
+ args = None
252
+ try:
253
+ args = parser.parse_args(argv)
254
+ if args.command == "help":
255
+ _print_help(parser, args.topic)
256
+ return 0
257
+ if args.command == "init":
258
+ selected_targets = (
259
+ _select_ai_tools() if args.select_tools else ((args.integrate,) if args.integrate else ())
260
+ )
261
+ if args.with_rules and (
262
+ not selected_targets
263
+ or any(target in {"generic", "skill"} for target in selected_targets)
264
+ ):
265
+ raise HandoffError(
266
+ "--with-rules 必须与具名客户端、--select-tools 或 --integrate all 一起使用"
267
+ )
268
+ init_result = initialize_project(args.path, name=args.name, force=args.force)
269
+ print(f"已{'创建' if init_result.created else '检查'}记忆目录:{Path(args.path).resolve() / '.ai-memory'}")
270
+ if selected_targets:
271
+ changed = []
272
+ for target in selected_targets:
273
+ changed.extend(
274
+ integrate(
275
+ args.path,
276
+ target,
277
+ with_rules=args.with_rules,
278
+ )
279
+ )
280
+ print(f"已更新 {len(changed)} 个 AI 接入文件")
281
+ elif args.select_tools:
282
+ print("已跳过 AI 工具接入")
283
+ return 0
284
+ if args.command == "save":
285
+ content = _read_source(args.source) if args.source else None
286
+ archive_result = archive_active(
287
+ args.path,
288
+ content=content,
289
+ allow_sensitive=args.allow_sensitive,
290
+ allow_large=args.allow_large,
291
+ )
292
+ if args.format == "json":
293
+ _print_json(
294
+ {
295
+ "schema_version": 1,
296
+ "ok": True,
297
+ "archive": str(archive_result.archive_path),
298
+ "saved_at": archive_result.saved_at,
299
+ "active_sha256": archive_result.active_sha256,
300
+ "repository": archive_result.repository_state.to_dict(),
301
+ "warnings": list(archive_result.warnings),
302
+ }
303
+ )
304
+ else:
305
+ print(f"已保存交接快照:{archive_result.archive_path}")
306
+ for warning in archive_result.warnings:
307
+ print(f"提示:{warning}")
308
+ return 0
309
+ if args.command == "resume":
310
+ print(render_resume(inspect_project(args.path), output_format=args.format), end="")
311
+ return 0
312
+ if args.command == "check":
313
+ report = inspect_project(args.path)
314
+ problems = list(report.validation_errors)
315
+ problems.extend(f"疑似 {item.kind}(第 {item.line} 行)" for item in report.secret_findings)
316
+ active_privacy_findings = (
317
+ find_personal_information(report.active) if args.privacy else []
318
+ )
319
+ repository_payload = report.repository.to_dict()
320
+ serialized_repository = json.dumps(
321
+ repository_payload, ensure_ascii=False, sort_keys=True, indent=2
322
+ )
323
+ repository_secret_findings = find_secrets(serialized_repository)
324
+ saved_repository = report.config.get("last_saved_repository")
325
+ if not isinstance(saved_repository, dict):
326
+ saved_repository = report.config.get("last_saved_git")
327
+ serialized_saved_repository = json.dumps(
328
+ saved_repository if isinstance(saved_repository, dict) else {},
329
+ ensure_ascii=False,
330
+ sort_keys=True,
331
+ indent=2,
332
+ )
333
+ serialized_drift = json.dumps(
334
+ list(report.drift), ensure_ascii=False, indent=2
335
+ )
336
+ repository_privacy_findings = (
337
+ find_personal_information(serialized_repository)
338
+ if args.privacy
339
+ else []
340
+ )
341
+ saved_repository_privacy_findings = (
342
+ find_personal_information(serialized_saved_repository)
343
+ if args.privacy
344
+ else []
345
+ )
346
+ drift_privacy_findings = (
347
+ find_personal_information(serialized_drift) if args.privacy else []
348
+ )
349
+ privacy_findings = [
350
+ {**asdict(item), "source": "active"}
351
+ for item in active_privacy_findings
352
+ ] + [
353
+ {**asdict(item), "source": "repository"}
354
+ for item in repository_privacy_findings
355
+ ] + [
356
+ {**asdict(item), "source": "saved_repository"}
357
+ for item in saved_repository_privacy_findings
358
+ ] + [
359
+ {**asdict(item), "source": "drift"}
360
+ for item in drift_privacy_findings
361
+ ]
362
+ if (
363
+ repository_secret_findings
364
+ or repository_privacy_findings
365
+ or saved_repository_privacy_findings
366
+ ):
367
+ repository_payload = {
368
+ "provider": report.repository.provider,
369
+ "redacted": True,
370
+ "note": "仓库元数据包含敏感或个人信息,已在检查输出中隐藏",
371
+ }
372
+ drift_payload = list(report.drift)
373
+ if drift_privacy_findings:
374
+ drift_payload = ["仓库漂移包含个人信息,已隐藏具体值"]
375
+ warnings = list(report.quality_warnings)
376
+ warnings.extend(
377
+ f"疑似 {item['kind']}({item['source']} 第 {item['line']} 行)"
378
+ for item in privacy_findings
379
+ )
380
+ ok = not problems and (not args.strict or not warnings)
381
+ if args.format == "json":
382
+ _print_json(
383
+ {
384
+ "schema_version": 1,
385
+ "ok": ok,
386
+ "strict": args.strict,
387
+ "privacy": args.privacy,
388
+ "problems": problems,
389
+ "warnings": warnings,
390
+ "privacy_findings": privacy_findings,
391
+ "repository": repository_payload,
392
+ "drift": drift_payload,
393
+ "active_sha256": report.active_sha256,
394
+ "last_saved_active_sha256": report.saved_active_sha256,
395
+ "active_matches_saved": report.active_matches_saved,
396
+ }
397
+ )
398
+ return 0 if ok else 2
399
+ if problems:
400
+ print("检查失败:", file=sys.stderr)
401
+ for problem in problems:
402
+ print(f"- {problem}", file=sys.stderr)
403
+ return 2
404
+ if args.strict and warnings:
405
+ print("严格检查失败:", file=sys.stderr)
406
+ for warning in warnings:
407
+ print(f"- {warning}", file=sys.stderr)
408
+ return 2
409
+ for warning in warnings:
410
+ print(f"提示:{warning}")
411
+ print("检查通过:记忆格式有效,未发现高置信度敏感信息。")
412
+ return 0
413
+ if args.command == "history":
414
+ print(
415
+ render_history(list_history(args.path), output_format=args.format),
416
+ end="",
417
+ )
418
+ return 0
419
+ if args.command == "show":
420
+ print(
421
+ render_snapshot(
422
+ show_snapshot(args.path, args.snapshot),
423
+ output_format=args.format,
424
+ ),
425
+ end="",
426
+ )
427
+ return 0
428
+ if args.command == "integrate":
429
+ changed = integrate(
430
+ args.path,
431
+ args.target,
432
+ with_rules=args.with_rules,
433
+ )
434
+ print(f"已更新 {len(changed)} 个 AI 接入文件")
435
+ return 0
436
+ parser.error("缺少命令")
437
+ return 2
438
+ except (HandoffError, ValueError) as exc:
439
+ if _json_requested(args):
440
+ _print_json(
441
+ {
442
+ "schema_version": 1,
443
+ "ok": False,
444
+ "error": {"code": "HANDOFF_ERROR", "message": str(exc)},
445
+ }
446
+ )
447
+ else:
448
+ print(f"错误:{exc}", file=sys.stderr)
449
+ return 2
450
+ except KeyboardInterrupt:
451
+ print("错误:操作已取消", file=sys.stderr)
452
+ return 130
453
+ except Exception as exc:
454
+ if _json_requested(args):
455
+ _print_json(
456
+ {
457
+ "schema_version": 1,
458
+ "ok": False,
459
+ "error": {
460
+ "code": "INTERNAL_ERROR",
461
+ "message": f"{type(exc).__name__}:{exc}",
462
+ },
463
+ }
464
+ )
465
+ else:
466
+ print(f"内部错误:{type(exc).__name__}:{exc}", file=sys.stderr)
467
+ return 1
468
+
469
+
470
+ def _json_requested(args: argparse.Namespace | None) -> bool:
471
+ return args is not None and getattr(args, "format", None) == "json"
472
+
473
+
474
+ def _print_json(payload: dict[str, object]) -> None:
475
+ print(json.dumps(payload, ensure_ascii=False, indent=2))
476
+
477
+
478
+ def _read_source(source: str) -> str:
479
+ if source == "-":
480
+ try:
481
+ content = sys.stdin.read(HARD_ACTIVE_LIMIT + 1)
482
+ except UnicodeError as exc:
483
+ raise HandoffError("标准输入必须是 UTF-8 文本") from exc
484
+ if len(content.encode("utf-8")) > HARD_ACTIVE_LIMIT:
485
+ raise HandoffError("标准输入超过 256KB 限制")
486
+ return content
487
+ path = Path(source).expanduser().resolve()
488
+ if not path.is_file() or path.stat().st_size > HARD_ACTIVE_LIMIT:
489
+ raise HandoffError(f"交接来源不存在或超过 256KB:{path}")
490
+ try:
491
+ return path.read_text(encoding="utf-8")
492
+ except UnicodeError as exc:
493
+ raise HandoffError(f"交接来源必须是 UTF-8 文本:{path}") from exc
494
+
495
+
496
+ def _select_ai_tools() -> tuple[str, ...]:
497
+ """显示零依赖多选列表;返回按菜单顺序去重后的接入目标。"""
498
+ print("请选择需要接入的 AI 编程工具(可多选):")
499
+ for index, target in enumerate(AI_TOOL_TARGETS, start=1):
500
+ print(f" {index:>2}. {AI_TOOL_LABELS[target]} ({target})")
501
+ print("输入编号并用逗号分隔;输入 all 选择全部;直接回车跳过。")
502
+ while True:
503
+ try:
504
+ answer = input("请选择:").strip().lower()
505
+ except EOFError as exc:
506
+ raise HandoffError("无法读取交互输入;非交互环境请使用 --integrate") from exc
507
+ if not answer:
508
+ return ()
509
+ if answer in {"all", "a"}:
510
+ return AI_TOOL_TARGETS
511
+ parts = [part for part in re.split(r"[,,\s]+", answer) if part]
512
+ if parts and all(part.isdigit() for part in parts):
513
+ indexes = [int(part) for part in parts]
514
+ if all(1 <= index <= len(AI_TOOL_TARGETS) for index in indexes):
515
+ selected = set(indexes)
516
+ return tuple(
517
+ target
518
+ for index, target in enumerate(AI_TOOL_TARGETS, start=1)
519
+ if index in selected
520
+ )
521
+ print(f"无效选择:请输入 1–{len(AI_TOOL_TARGETS)} 的编号、all,或直接回车。")
522
+
523
+
524
+ def _print_help(parser: argparse.ArgumentParser, topic: str | None) -> None:
525
+ if topic is None:
526
+ parser.print_help()
527
+ return
528
+ for action in parser._actions:
529
+ if isinstance(action, argparse._SubParsersAction):
530
+ action.choices[topic].print_help()
531
+ return
532
+ raise RuntimeError("CLI 子命令帮助不可用")
533
+
534
+
535
+ def _localize_help(parser: argparse.ArgumentParser) -> None:
536
+ """让 argparse 的固定帮助标签与项目中文 CLI 保持一致。"""
537
+ parser._positionals.title = "位置参数"
538
+ parser._optionals.title = "选项"
539
+ for action in parser._actions:
540
+ if action.dest == "help":
541
+ action.help = "显示帮助并退出"
542
+
543
+
544
+ def _configure_utf8_stdio() -> None:
545
+ """统一 Windows 旧代码页与管道场景下的 CLI 输出编码。"""
546
+ reconfigure_stdin = getattr(sys.stdin, "reconfigure", None)
547
+ if callable(reconfigure_stdin):
548
+ reconfigure_stdin(encoding="utf-8", errors="strict")
549
+ for stream in (sys.stdout, sys.stderr):
550
+ reconfigure = getattr(stream, "reconfigure", None)
551
+ if callable(reconfigure):
552
+ reconfigure(encoding="utf-8", errors="replace")
553
+
554
+
555
+ if __name__ == "__main__":
556
+ raise SystemExit(main())