braid-coding-agent 0.1.0__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.
Files changed (192) hide show
  1. braid_coding_agent/__init__.py +13 -0
  2. braid_coding_agent/assembly.py +460 -0
  3. braid_coding_agent/cancellation.py +25 -0
  4. braid_coding_agent/checkpoint/__init__.py +106 -0
  5. braid_coding_agent/checkpoint/git.py +305 -0
  6. braid_coding_agent/checkpoint/settings.py +26 -0
  7. braid_coding_agent/checkpoint/store.py +1261 -0
  8. braid_coding_agent/checkpoint/workspace.py +220 -0
  9. braid_coding_agent/cli.py +2168 -0
  10. braid_coding_agent/commands/__init__.py +50 -0
  11. braid_coding_agent/commands/auth.py +161 -0
  12. braid_coding_agent/commands/config.py +180 -0
  13. braid_coding_agent/commands/doctor.py +511 -0
  14. braid_coding_agent/commands/mcp.py +928 -0
  15. braid_coding_agent/commands/models.py +95 -0
  16. braid_coding_agent/commands/setup.py +89 -0
  17. braid_coding_agent/commands/uninstall.py +277 -0
  18. braid_coding_agent/commands/upgrade.py +381 -0
  19. braid_coding_agent/compaction/__init__.py +174 -0
  20. braid_coding_agent/compaction/prepare.py +430 -0
  21. braid_coding_agent/compaction/summarize.py +542 -0
  22. braid_coding_agent/compaction/tokens.py +204 -0
  23. braid_coding_agent/compaction/tool_results.py +196 -0
  24. braid_coding_agent/compaction/utils.py +181 -0
  25. braid_coding_agent/config.py +2776 -0
  26. braid_coding_agent/config_files.py +191 -0
  27. braid_coding_agent/credentials.py +252 -0
  28. braid_coding_agent/discovery.py +415 -0
  29. braid_coding_agent/extensions/__init__.py +77 -0
  30. braid_coding_agent/extensions/api.py +480 -0
  31. braid_coding_agent/extensions/runner.py +553 -0
  32. braid_coding_agent/formatting/__init__.py +62 -0
  33. braid_coding_agent/formatting/settings.py +87 -0
  34. braid_coding_agent/formatting/tool.py +179 -0
  35. braid_coding_agent/lsp/__init__.py +105 -0
  36. braid_coding_agent/lsp/client.py +546 -0
  37. braid_coding_agent/lsp/manager.py +187 -0
  38. braid_coding_agent/lsp/model.py +316 -0
  39. braid_coding_agent/lsp/protocol.py +105 -0
  40. braid_coding_agent/lsp/settings.py +120 -0
  41. braid_coding_agent/lsp/tool.py +429 -0
  42. braid_coding_agent/mcp/__init__.py +101 -0
  43. braid_coding_agent/mcp/cache.py +230 -0
  44. braid_coding_agent/mcp/catalog.py +108 -0
  45. braid_coding_agent/mcp/config.py +664 -0
  46. braid_coding_agent/mcp/config_store.py +142 -0
  47. braid_coding_agent/mcp/inspector.py +85 -0
  48. braid_coding_agent/mcp/panel.py +254 -0
  49. braid_coding_agent/mcp/runtime.py +1060 -0
  50. braid_coding_agent/mcp/tools.py +579 -0
  51. braid_coding_agent/mcp/trust.py +150 -0
  52. braid_coding_agent/mcp/tui_panel.py +444 -0
  53. braid_coding_agent/messages.py +152 -0
  54. braid_coding_agent/models_view.py +105 -0
  55. braid_coding_agent/modes/__init__.py +64 -0
  56. braid_coding_agent/modes/json_mode.py +480 -0
  57. braid_coding_agent/modes/lifecycle.py +217 -0
  58. braid_coding_agent/modes/print_mode.py +257 -0
  59. braid_coding_agent/modes/repl.py +2687 -0
  60. braid_coding_agent/modes/repl_commands.py +263 -0
  61. braid_coding_agent/modes/rpc.py +953 -0
  62. braid_coding_agent/modes/skill_commands.py +88 -0
  63. braid_coding_agent/modes/tui.py +2226 -0
  64. braid_coding_agent/modes/tui_control.py +90 -0
  65. braid_coding_agent/modes/tui_model.py +1043 -0
  66. braid_coding_agent/modes/tui_render.py +327 -0
  67. braid_coding_agent/modes/tui_rich.py +751 -0
  68. braid_coding_agent/modes/tui_style.py +42 -0
  69. braid_coding_agent/modes/wire.py +81 -0
  70. braid_coding_agent/netsafe.py +82 -0
  71. braid_coding_agent/network/__init__.py +20 -0
  72. braid_coding_agent/network/cache.py +77 -0
  73. braid_coding_agent/network/fetch.py +311 -0
  74. braid_coding_agent/network/html_text.py +160 -0
  75. braid_coding_agent/network/search.py +347 -0
  76. braid_coding_agent/network/settings.py +103 -0
  77. braid_coding_agent/network/urls.py +89 -0
  78. braid_coding_agent/observability/__init__.py +101 -0
  79. braid_coding_agent/observability/audit.py +124 -0
  80. braid_coding_agent/observability/collector.py +314 -0
  81. braid_coding_agent/observability/exporter.py +74 -0
  82. braid_coding_agent/observability/logging_setup.py +149 -0
  83. braid_coding_agent/observability/redaction.py +96 -0
  84. braid_coding_agent/observability/settings.py +29 -0
  85. braid_coding_agent/observability/spans.py +239 -0
  86. braid_coding_agent/permissions/__init__.py +185 -0
  87. braid_coding_agent/permissions/command.py +586 -0
  88. braid_coding_agent/permissions/engine.py +522 -0
  89. braid_coding_agent/permissions/evaluate.py +309 -0
  90. braid_coding_agent/permissions/matching.py +233 -0
  91. braid_coding_agent/permissions/model.py +278 -0
  92. braid_coding_agent/permissions/policy.py +99 -0
  93. braid_coding_agent/permissions/readonly.py +236 -0
  94. braid_coding_agent/permissions/store.py +379 -0
  95. braid_coding_agent/project_init.py +313 -0
  96. braid_coding_agent/prompt/__init__.py +98 -0
  97. braid_coding_agent/prompt/context_files.py +253 -0
  98. braid_coding_agent/prompt/project_context.py +172 -0
  99. braid_coding_agent/prompt/system_prompt.py +378 -0
  100. braid_coding_agent/questions.py +71 -0
  101. braid_coding_agent/render/__init__.py +56 -0
  102. braid_coding_agent/render/batch.py +66 -0
  103. braid_coding_agent/render/history.py +143 -0
  104. braid_coding_agent/render/stream.py +823 -0
  105. braid_coding_agent/render/theme.py +243 -0
  106. braid_coding_agent/sandbox/__init__.py +89 -0
  107. braid_coding_agent/sandbox/backend.py +184 -0
  108. braid_coding_agent/sandbox/bubblewrap.py +96 -0
  109. braid_coding_agent/sandbox/operations.py +301 -0
  110. braid_coding_agent/sandbox/policy.py +221 -0
  111. braid_coding_agent/sandbox/proxy.py +320 -0
  112. braid_coding_agent/sandbox/seatbelt.py +222 -0
  113. braid_coding_agent/sdk/__init__.py +31 -0
  114. braid_coding_agent/sdk/async_client.py +366 -0
  115. braid_coding_agent/sdk/client.py +386 -0
  116. braid_coding_agent/sdk/errors.py +52 -0
  117. braid_coding_agent/sdk/events.py +162 -0
  118. braid_coding_agent/sdk/types.py +63 -0
  119. braid_coding_agent/sdk/wire.py +59 -0
  120. braid_coding_agent/server/__init__.py +54 -0
  121. braid_coding_agent/server/errors.py +52 -0
  122. braid_coding_agent/server/http_server.py +419 -0
  123. braid_coding_agent/server/hub.py +530 -0
  124. braid_coding_agent/server/openapi.py +157 -0
  125. braid_coding_agent/server/registry.py +354 -0
  126. braid_coding_agent/server/router.py +275 -0
  127. braid_coding_agent/server/run.py +148 -0
  128. braid_coding_agent/server/schema.py +194 -0
  129. braid_coding_agent/server/service.py +975 -0
  130. braid_coding_agent/session/__init__.py +293 -0
  131. braid_coding_agent/session/agent_session.py +2706 -0
  132. braid_coding_agent/session/context_breakdown.py +302 -0
  133. braid_coding_agent/session/discovery.py +212 -0
  134. braid_coding_agent/session/entries.py +809 -0
  135. braid_coding_agent/session/evidence.py +295 -0
  136. braid_coding_agent/session/lock.py +176 -0
  137. braid_coding_agent/session/manager.py +1185 -0
  138. braid_coding_agent/session/plan.py +243 -0
  139. braid_coding_agent/session/plan_mode.py +423 -0
  140. braid_coding_agent/session/projection.py +262 -0
  141. braid_coding_agent/session/rewind.py +257 -0
  142. braid_coding_agent/session/status.py +240 -0
  143. braid_coding_agent/settings.py +94 -0
  144. braid_coding_agent/skills/__init__.py +70 -0
  145. braid_coding_agent/skills/loader.py +681 -0
  146. braid_coding_agent/startup/__init__.py +76 -0
  147. braid_coding_agent/startup/cache.py +72 -0
  148. braid_coding_agent/startup/diagnostics.py +37 -0
  149. braid_coding_agent/startup/monitor.py +245 -0
  150. braid_coding_agent/startup/phases.py +79 -0
  151. braid_coding_agent/startup/project.py +165 -0
  152. braid_coding_agent/startup/report.py +560 -0
  153. braid_coding_agent/startup/scheduler.py +347 -0
  154. braid_coding_agent/statusline.py +163 -0
  155. braid_coding_agent/subagents/__init__.py +22 -0
  156. braid_coding_agent/subagents/contract.py +75 -0
  157. braid_coding_agent/subagents/definitions.py +583 -0
  158. braid_coding_agent/subagents/registry.py +277 -0
  159. braid_coding_agent/subagents/runtime.py +610 -0
  160. braid_coding_agent/subagents/settings.py +156 -0
  161. braid_coding_agent/subagents/worktree.py +63 -0
  162. braid_coding_agent/tools/__init__.py +327 -0
  163. braid_coding_agent/tools/args.py +87 -0
  164. braid_coding_agent/tools/bash.py +359 -0
  165. braid_coding_agent/tools/edit.py +298 -0
  166. braid_coding_agent/tools/edit_diff.py +344 -0
  167. braid_coding_agent/tools/find.py +158 -0
  168. braid_coding_agent/tools/grep.py +305 -0
  169. braid_coding_agent/tools/ignore.py +198 -0
  170. braid_coding_agent/tools/ls.py +127 -0
  171. braid_coding_agent/tools/mutation_queue.py +90 -0
  172. braid_coding_agent/tools/operations.py +274 -0
  173. braid_coding_agent/tools/output_accumulator.py +282 -0
  174. braid_coding_agent/tools/output_store.py +244 -0
  175. braid_coding_agent/tools/path_utils.py +91 -0
  176. braid_coding_agent/tools/plan.py +141 -0
  177. braid_coding_agent/tools/prompt_notes.py +52 -0
  178. braid_coding_agent/tools/question.py +180 -0
  179. braid_coding_agent/tools/read.py +223 -0
  180. braid_coding_agent/tools/submit_plan.py +102 -0
  181. braid_coding_agent/tools/truncate.py +423 -0
  182. braid_coding_agent/tools/write.py +100 -0
  183. braid_coding_agent/untrusted.py +50 -0
  184. braid_coding_agent/verify/__init__.py +78 -0
  185. braid_coding_agent/verify/runner.py +260 -0
  186. braid_coding_agent/verify/settings.py +64 -0
  187. braid_coding_agent/verify/tool.py +143 -0
  188. braid_coding_agent-0.1.0.dist-info/METADATA +19 -0
  189. braid_coding_agent-0.1.0.dist-info/RECORD +192 -0
  190. braid_coding_agent-0.1.0.dist-info/WHEEL +4 -0
  191. braid_coding_agent-0.1.0.dist-info/entry_points.txt +3 -0
  192. braid_coding_agent-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,1261 @@
1
+ """检查点:把"模型改了什么"变成可撤销的数据。
2
+
3
+ ## 为什么是影子仓库
4
+
5
+ 撤销要回答两个问题:**改动前是什么样**、**改了什么**。前者是内容,后者是差异。
6
+ 用一棵自己的 git 树同时解决两者:树的每个节点都是内容哈希,同一份内容只存一次;
7
+ 两棵树之间的差异由 ``git diff`` 直接给出,不需要自己实现 unified diff。
8
+
9
+ 影子仓库的位置是 ``<session_dir>/<session_id>/snapshots``,``GIT_DIR`` 指向它,
10
+ ``GIT_WORK_TREE`` 指向工作目录。它**不碰用户自己的** ``.git``:那里的索引、
11
+ HEAD、暂存区都不该因为"我想撤销一次编辑"而改变。
12
+
13
+ ## 三个层次,各管一件事
14
+
15
+ | 层 | 时机 | 记什么 | 谁用 |
16
+ |---|---|---|---|
17
+ | 基线树 | 会话第一次使用时 | 工作区全部文件的内容树 | ``/diff`` 的起点 |
18
+ | 回合树 | 每次用户回合开始与结束 | 这一回合前后的两棵树 | ``/undo``、``/redo`` |
19
+ | 文件前像 | 每次 ``write`` / ``edit`` 之前 | 目标文件的内容 blob | 被 ``.gitignore`` 排除的文件 |
20
+
21
+ 第三层不是冗余。``git`` 不跟踪被忽略的文件,而模型完全可能改一个 ``.env.local``:
22
+ 没有文件前像,撤销会漏掉它。反过来,只有文件前像也不行——``bash`` 可以改任意文件,
23
+ 根本不会经过工具钩子。
24
+
25
+ ## 回合与撤销栈
26
+
27
+ 一个"回合"是一次 ``prompt`` 到 ``agent_settled`` 的全过程,包含自动重试、溢出恢复
28
+ 与后续追问。撤销恢复的是**这一回合开始之前**的状态,因此用户看到的粒度是
29
+ "我刚才让你做的那件事",而不是"某一个工具调用"。
30
+
31
+ 撤销栈只压入**真的改了文件**的回合:问一句话不会让 ``/undo`` 空转一次。
32
+ 新回合产生改动时清空重做栈——文件已经被改成别的样子,把旧状态再"重做"上去
33
+ 只是在覆盖用户后来的劳动。
34
+
35
+ ## 日志与恢复
36
+
37
+ 回合日志是 ``snapshots/turns.log``,只追加。进程在任何一步被杀掉,日志都能
38
+ 告诉我们"有一回合开了没合",下次打开时把它标成 broken:撤销仍然可用(它只需要
39
+ ``before_tree``),重做不可用(没有可信的结束状态)。压缩、恢复会话、换进程
40
+ 都不影响这条链——日志与仓库都在磁盘上。
41
+
42
+ ## 失败的方向
43
+
44
+ - ``write`` / ``edit`` 之前拿不到前像:**拒绝执行**。一次改不动的编辑,好过一次
45
+ 撤不回的编辑。
46
+ - ``bash`` 之后拿不到结束树:命令已经跑完,副作用已经发生,把它翻成错误只会让
47
+ 模型以为命令失败。记录错误、继续,并在 ``/status`` 里说出来。
48
+ """
49
+
50
+ from __future__ import annotations
51
+
52
+ import asyncio
53
+ import json
54
+ import logging
55
+ import os
56
+ import stat
57
+ from collections.abc import Sequence
58
+ from dataclasses import dataclass, field
59
+ from pathlib import Path
60
+ from typing import Final, Literal
61
+
62
+ from braid_ai.cancel import CancelToken
63
+ from braid_ai.types import JsonValue
64
+ from braid_ai.utils.clock import Clock, SystemClock
65
+ from braid_coding_agent.checkpoint.git import SHADOW_CONFIG, Git, GitError
66
+ from braid_coding_agent.checkpoint.settings import (
67
+ DEFAULT_MAX_FILE_BYTES,
68
+ CheckpointSettings,
69
+ )
70
+ from braid_coding_agent.session.entries import iso_from_ms
71
+
72
+ logger = logging.getLogger(__name__)
73
+
74
+ #: 影子仓库目录名(相对会话目录)。
75
+ SNAPSHOTS_DIR: Final[str] = "snapshots"
76
+ #: 回合日志文件名(在影子仓库目录里)。故意不用 ``.jsonl`` 后缀:会话目录下按
77
+ #: ``*.jsonl`` 扫描的工具会把任何同名文件当成一份会话。
78
+ LOG_NAME: Final[str] = "turns.log"
79
+ #: 日志格式版本。结构变化时递增,旧日志按读得懂的部分读入。
80
+ LOG_VERSION: Final[int] = 1
81
+ #: ``git checkout-index`` 单批路径数量。避免一次 argv 超过 ARG_MAX。
82
+ _CHECKOUT_BATCH: Final[int] = 200
83
+
84
+ type TurnStatus = Literal["open", "closed", "broken"]
85
+ type ChangeStatus = Literal["added", "modified", "deleted"]
86
+ type ChangeSource = Literal["tree", "file"]
87
+ type SkipReason = Literal["symlink", "hardlink", "too_large", "unreadable"]
88
+
89
+ #: 会被检查点记录的工具。
90
+ FILE_TOOLS: Final[frozenset[str]] = frozenset({"write", "edit"})
91
+ SHELL_TOOLS: Final[frozenset[str]] = frozenset({"bash"})
92
+
93
+
94
+ class CheckpointError(RuntimeError):
95
+ """检查点不可用或不一致。调用方要么拒绝这次工具调用,要么关掉检查点。"""
96
+
97
+
98
+ @dataclass(slots=True, frozen=True)
99
+ class FileChange:
100
+ """一个文件在一次回合里的变化。``before`` / ``after`` 是 blob 哈希,``None`` 表示不存在。"""
101
+
102
+ path: str
103
+ status: ChangeStatus
104
+ before: str | None
105
+ after: str | None
106
+ source: ChangeSource = "tree"
107
+
108
+ def to_json(self) -> dict[str, JsonValue]:
109
+ return {
110
+ "path": self.path,
111
+ "status": self.status,
112
+ "before": self.before,
113
+ "after": self.after,
114
+ "source": self.source,
115
+ }
116
+
117
+ @classmethod
118
+ def from_json(cls, raw: JsonValue) -> FileChange:
119
+ if not isinstance(raw, dict):
120
+ raise CheckpointError("检查点日志里的 changes 条目不是对象")
121
+ path = raw.get("path")
122
+ status = raw.get("status")
123
+ if not isinstance(path, str) or status not in ("added", "modified", "deleted"):
124
+ raise CheckpointError(f"检查点日志里的 changes 条目不完整:{raw!r}")
125
+ before = raw.get("before")
126
+ after = raw.get("after")
127
+ source = raw.get("source")
128
+ return cls(
129
+ path=path,
130
+ status=status,
131
+ before=before if isinstance(before, str) else None,
132
+ after=after if isinstance(after, str) else None,
133
+ source="file" if source == "file" else "tree",
134
+ )
135
+
136
+
137
+ @dataclass(slots=True, frozen=True)
138
+ class SkippedFile:
139
+ """没有进入快照的文件与原因。用户在 ``/status`` 里看到它。"""
140
+
141
+ path: str
142
+ reason: SkipReason
143
+
144
+ def to_json(self) -> dict[str, JsonValue]:
145
+ return {"path": self.path, "reason": self.reason}
146
+
147
+ def describe(self) -> str:
148
+ labels = {
149
+ "symlink": "符号链接",
150
+ "hardlink": "硬链接",
151
+ "too_large": "超过大小上限",
152
+ "unreadable": "当前用户读不到",
153
+ }
154
+ return f"{self.path}({labels[self.reason]})"
155
+
156
+
157
+ @dataclass(slots=True, frozen=True)
158
+ class CheckpointTurn:
159
+ """一个用户回合的文件状态。``before_tree`` 是撤销的目标。"""
160
+
161
+ id: str
162
+ sequence: int
163
+ started_at: str
164
+ before_tree: str
165
+ after_tree: str | None = None
166
+ status: TurnStatus = "open"
167
+ finished_at: str | None = None
168
+ changes: tuple[FileChange, ...] = ()
169
+ #: 发起这一回合的用户消息条目 id。会话层在用户消息落盘之后绑定,回退靠它
170
+ #: 把"树上的一句话"与"那一刻的工作区"对起来。
171
+ message_entry_id: str | None = None
172
+
173
+ @property
174
+ def paths(self) -> tuple[str, ...]:
175
+ return tuple(change.path for change in self.changes)
176
+
177
+ def summary(self) -> str:
178
+ """一行给人的说明:``第 2 回合 · 3 个文件 · 10:41``。"""
179
+ return f"第 {self.sequence} 回合 · {len(self.changes)} 个文件 · {self.started_at[11:19]}"
180
+
181
+
182
+ @dataclass(slots=True, frozen=True)
183
+ class UndoResult:
184
+ """撤销/重做的结果。``applied=False`` 时 ``message`` 说明为什么。"""
185
+
186
+ applied: bool
187
+ message: str
188
+ turn: CheckpointTurn | None = None
189
+ changes: tuple[FileChange, ...] = ()
190
+ undo_depth: int = 0
191
+ redo_depth: int = 0
192
+
193
+
194
+ @dataclass(slots=True, frozen=True)
195
+ class SessionDiff:
196
+ """会话基线到当前工作区的差异。"""
197
+
198
+ baseline_tree: str
199
+ current_tree: str
200
+ changes: tuple[FileChange, ...]
201
+ patch: str
202
+ truncated: bool = False
203
+
204
+
205
+ @dataclass(slots=True, frozen=True)
206
+ class CheckpointStatus:
207
+ """``/status`` 与会话状态查询用的只读快照。"""
208
+
209
+ enabled: bool
210
+ repo: str | None
211
+ baseline_tree: str | None
212
+ turns: int
213
+ undoable: int
214
+ redoable: int
215
+ broken: int
216
+ skipped: tuple[SkippedFile, ...]
217
+ last_error: str | None
218
+
219
+ def summary(self) -> str:
220
+ if not self.enabled:
221
+ return "检查点未启用"
222
+ undone = f"{self.undoable} 可撤销" if self.undoable else "无可撤销回合"
223
+ redo = f",{self.redoable} 可重做" if self.redoable else ""
224
+ return f"{self.turns} 个回合 · {undone}{redo}"
225
+
226
+
227
+ @dataclass(slots=True)
228
+ class _Draft:
229
+ """日志里一个回合的累积状态。写入前都在这里攒着。"""
230
+
231
+ id: str
232
+ sequence: int
233
+ started_at: str
234
+ before_tree: str
235
+ after_tree: str | None = None
236
+ status: TurnStatus = "open"
237
+ finished_at: str | None = None
238
+ changes: dict[str, FileChange] = field(default_factory=dict[str, FileChange])
239
+ #: 这一回合里 ``write`` / ``edit`` 前记下的文件前像:路径 → blob 哈希。
240
+ #: ``None`` 表示调用前这个文件不存在。
241
+ files: dict[str, str | None] = field(default_factory=dict[str, str | None])
242
+ shells: int = 0
243
+ #: 发起这一回合的用户消息条目 id。第一个用户消息落盘时绑定,之后不再改。
244
+ message_entry_id: str | None = None
245
+
246
+ def turn(self) -> CheckpointTurn:
247
+ ordered = tuple(self.changes[path] for path in sorted(self.changes))
248
+ return CheckpointTurn(
249
+ id=self.id,
250
+ sequence=self.sequence,
251
+ started_at=self.started_at,
252
+ before_tree=self.before_tree,
253
+ after_tree=self.after_tree,
254
+ status=self.status,
255
+ finished_at=self.finished_at,
256
+ changes=ordered,
257
+ message_entry_id=self.message_entry_id,
258
+ )
259
+
260
+
261
+ class CheckpointStore:
262
+ """一个会话的影子仓库、回合日志与撤销栈。
263
+
264
+ 构造是纯内存操作;第一次 ``await`` 时才建仓库、读日志、抓基线
265
+ (:meth:`ensure_ready`)。这样组合根可以同步装配它,而所有 I/O 都发生在
266
+ 事件循环里。
267
+
268
+ :param cwd: 工作目录,也是影子仓库的 ``GIT_WORK_TREE``。
269
+ :param session_dir: 会话目录(``<...>/sessions/--<cwd编码>--``)。
270
+ :param session_id: 会话 id,用作快照子目录名。
271
+ :param git: 可替换的 git 运行器,测试用它指向一个不存在的可执行文件。
272
+ """
273
+
274
+ def __init__(
275
+ self,
276
+ *,
277
+ cwd: str,
278
+ session_dir: str,
279
+ session_id: str,
280
+ clock: Clock | None = None,
281
+ settings: CheckpointSettings | None = None,
282
+ git: Git | None = None,
283
+ ) -> None:
284
+ self._cwd = os.path.abspath(cwd)
285
+ self._session_root = os.path.abspath(session_dir)
286
+ self._root = os.path.join(self._session_root, session_id)
287
+ self._repo = os.path.join(self._root, SNAPSHOTS_DIR)
288
+ self._log = os.path.join(self._repo, LOG_NAME)
289
+ self._clock: Clock = clock if clock is not None else SystemClock()
290
+ self._settings = settings if settings is not None else CheckpointSettings()
291
+ self._git = (
292
+ git
293
+ if git is not None
294
+ else Git(
295
+ cwd=self._cwd,
296
+ git_dir=self._repo,
297
+ work_tree=self._cwd,
298
+ config=SHADOW_CONFIG,
299
+ )
300
+ )
301
+ self._ready = False
302
+ self._lock = asyncio.Lock()
303
+ self._turns: list[CheckpointTurn] = []
304
+ self._undo: list[CheckpointTurn] = []
305
+ self._redo: list[CheckpointTurn] = []
306
+ self._draft: _Draft | None = None
307
+ self._pending_shell: dict[str, str] = {}
308
+ self._baseline: str | None = None
309
+ self._skipped: tuple[SkippedFile, ...] = ()
310
+ self._last_error: str | None = None
311
+ self._sequence = 0
312
+
313
+ # ------------------------------------------------------------- 只读状态
314
+
315
+ @property
316
+ def repo_path(self) -> str:
317
+ """影子仓库目录(``GIT_DIR``)。"""
318
+ return self._repo
319
+
320
+ @property
321
+ def log_path(self) -> str:
322
+ """回合日志路径。"""
323
+ return self._log
324
+
325
+ @property
326
+ def settings(self) -> CheckpointSettings:
327
+ return self._settings
328
+
329
+ @property
330
+ def turns(self) -> tuple[CheckpointTurn, ...]:
331
+ """有、且改动过文件的回合,按时间顺序。没有改动的回合不进这里。"""
332
+ return tuple(turn for turn in self._turns if turn.changes)
333
+
334
+ def status(self) -> CheckpointStatus:
335
+ """内存里的只读快照。没初始化过时计数为 0。"""
336
+ changed = self.turns
337
+ return CheckpointStatus(
338
+ enabled=True,
339
+ repo=self._repo if self._ready else None,
340
+ baseline_tree=self._baseline,
341
+ turns=len(changed),
342
+ undoable=len(self._undo),
343
+ redoable=len(self._redo),
344
+ broken=sum(1 for turn in self._turns if turn.status == "broken"),
345
+ skipped=self._skipped,
346
+ last_error=self._last_error,
347
+ )
348
+
349
+ # --------------------------------------------------------------- 初始化
350
+
351
+ async def ensure_ready(self) -> None:
352
+ """建仓库、读日志、补基线。可重复调用;并发调用只真正执行一次。"""
353
+ if self._ready:
354
+ return
355
+ async with self._lock:
356
+ if self._ready:
357
+ return
358
+ await self._initialize()
359
+ self._ready = True
360
+
361
+ async def _initialize(self) -> None:
362
+ os.makedirs(self._root, exist_ok=True)
363
+ self._load_log()
364
+ await self._git.init(exclude=self._exclude_patterns())
365
+ if self._baseline is None:
366
+ self._baseline = await self._capture()
367
+ self._append({"type": "baseline", "tree": self._baseline})
368
+ self._close_open_drafts()
369
+
370
+ def _excluded_prefixes(self) -> tuple[str, ...]:
371
+ """工作区里不该进快照的两处:影子仓库自己与会话目录。
372
+
373
+ 两处都可能落在工作区内部(``--session-dir ./.sessions``,或 ``BRAID_AGENT_DIR``
374
+ 指向项目内)。影子仓库不排除,下一次抓取会把上一次的对象库再抓一遍,体积与耗时
375
+ 按平方增长;会话目录不排除,``/rewind`` 的整树恢复会把用户自己的会话文件当成
376
+ "目标快照之后新增的文件"删掉——回退一次就丢掉一份会话。
377
+
378
+ 落在工作区外的路径返回空:``relpath`` 以 ``..`` 开头,不是候选。
379
+ """
380
+ prefixes: list[str] = []
381
+ for path in (self._repo, self._session_root):
382
+ relative = os.path.relpath(path, self._cwd)
383
+ if relative.startswith("..") or os.path.isabs(relative) or relative in (".", ""):
384
+ continue
385
+ prefixes.append(relative.replace(os.sep, "/").rstrip("/") + "/")
386
+ return tuple(prefixes)
387
+
388
+ def _exclude_patterns(self) -> tuple[str, ...]:
389
+ """写进 ``info/exclude`` 的模式:用户配置的,加上 :meth:`_excluded_prefixes`。"""
390
+ patterns = list(self._settings.exclude)
391
+ for prefix in self._excluded_prefixes():
392
+ patterns.insert(0, "/" + prefix)
393
+ return tuple(patterns)
394
+
395
+ def _load_log(self) -> None:
396
+ """读回回合日志。最后一行截断可以容忍,中间坏行不行。"""
397
+ path = Path(self._log)
398
+ if not path.exists():
399
+ self._append(
400
+ {
401
+ "type": "checkpoint",
402
+ "version": LOG_VERSION,
403
+ "cwd": self._cwd,
404
+ "createdAt": self._now(),
405
+ }
406
+ )
407
+ return
408
+ lines = path.read_text(encoding="utf-8").splitlines()
409
+ drafts: dict[str, _Draft] = {}
410
+ order: list[str] = []
411
+ cuts: list[int] = []
412
+ for index, line in enumerate(lines):
413
+ if not line.strip():
414
+ continue
415
+ try:
416
+ parsed: JsonValue = json.loads(line)
417
+ except json.JSONDecodeError:
418
+ if index == len(lines) - 1:
419
+ break # 写入中途崩溃留下的半行
420
+ raise CheckpointError(f"{self._log} 第 {index + 1} 行不是合法 JSON") from None
421
+ if not isinstance(parsed, dict):
422
+ raise CheckpointError(f"{self._log} 第 {index + 1} 行不是 JSON 对象")
423
+ record: dict[str, JsonValue] = parsed
424
+ kind = record.get("type")
425
+ if kind in ("checkpoint", "shell"):
426
+ continue
427
+ if kind == "baseline":
428
+ tree = record.get("tree")
429
+ if isinstance(tree, str):
430
+ self._baseline = tree
431
+ continue
432
+ if kind == "turn":
433
+ draft = self._draft_from_json(record)
434
+ drafts[draft.id] = draft
435
+ order.append(draft.id)
436
+ self._sequence = max(self._sequence, draft.sequence)
437
+ continue
438
+ if kind == "turn_end":
439
+ self._apply_turn_end(drafts, record)
440
+ continue
441
+ if kind == "turn_bind":
442
+ self._apply_turn_bind(drafts, record)
443
+ continue
444
+ if kind == "rewind":
445
+ cut = record.get("toSequence")
446
+ if isinstance(cut, int) and not isinstance(cut, bool):
447
+ cuts.append(cut)
448
+ continue
449
+ if kind == "file":
450
+ self._apply_file(drafts, record)
451
+ continue
452
+ if kind in ("undo", "redo", "clear_redo"):
453
+ continue # 撤销栈在回合都读完之后统一重放
454
+ raise CheckpointError(f"{self._log} 含未知记录类型 {kind!r}")
455
+
456
+ turns = [drafts[key].turn() for key in order]
457
+ for cut in cuts:
458
+ # 回退记录按出现顺序生效:后写的回退只可能落在更晚的回合上,
459
+ # 逐条过滤让"先退到第 3 回合、后退到第 5 回合"两条记录同时成立。
460
+ turns = [turn for turn in turns if turn.sequence < cut]
461
+ self._turns = turns
462
+ for turn in turns:
463
+ if turn.status != "open" and turn.changes:
464
+ self._undo.append(turn)
465
+ self._replay_undo_records(lines, drafts, {turn.id for turn in turns})
466
+
467
+ def _draft_from_json(self, record: dict[str, JsonValue]) -> _Draft:
468
+ turn_id = record.get("id")
469
+ sequence = record.get("sequence")
470
+ started = record.get("startedAt")
471
+ before = record.get("beforeTree")
472
+ if (
473
+ not isinstance(turn_id, str)
474
+ or not isinstance(sequence, int)
475
+ or not isinstance(started, str)
476
+ or not isinstance(before, str)
477
+ ):
478
+ raise CheckpointError(f"检查点日志里的 turn 条目不完整:{record!r}")
479
+ return _Draft(id=turn_id, sequence=sequence, started_at=started, before_tree=before)
480
+
481
+ def _apply_turn_end(self, drafts: dict[str, _Draft], record: dict[str, JsonValue]) -> None:
482
+ turn_id = record.get("id")
483
+ draft = drafts.get(turn_id) if isinstance(turn_id, str) else None
484
+ if draft is None:
485
+ raise CheckpointError(f"检查点日志里的 turn_end 找不到对应回合:{turn_id!r}")
486
+ after = record.get("afterTree")
487
+ draft.after_tree = after if isinstance(after, str) else None
488
+ finished = record.get("finishedAt")
489
+ draft.finished_at = finished if isinstance(finished, str) else None
490
+ status = record.get("status")
491
+ draft.status = "broken" if status == "broken" else "closed"
492
+ raw_changes = record.get("changes")
493
+ if isinstance(raw_changes, list):
494
+ for item in raw_changes:
495
+ change = FileChange.from_json(item)
496
+ draft.changes[change.path] = change
497
+
498
+ def _apply_file(self, drafts: dict[str, _Draft], record: dict[str, JsonValue]) -> None:
499
+ turn_id = record.get("turn")
500
+ draft = drafts.get(turn_id) if isinstance(turn_id, str) else None
501
+ if draft is None:
502
+ raise CheckpointError(f"检查点日志里的 file 记录找不到对应回合:{turn_id!r}")
503
+ path = record.get("path")
504
+ if isinstance(path, str):
505
+ before = record.get("before")
506
+ draft.files.setdefault(path, before if isinstance(before, str) else None)
507
+
508
+ def _apply_turn_bind(self, drafts: dict[str, _Draft], record: dict[str, JsonValue]) -> None:
509
+ turn_id = record.get("id")
510
+ draft = drafts.get(turn_id) if isinstance(turn_id, str) else None
511
+ if draft is None:
512
+ raise CheckpointError(f"检查点日志里的 turn_bind 找不到对应回合:{turn_id!r}")
513
+ entry_id = record.get("messageEntryId")
514
+ if isinstance(entry_id, str):
515
+ draft.message_entry_id = entry_id
516
+
517
+ def _replay_undo_records(
518
+ self, lines: Sequence[str], drafts: dict[str, _Draft], surviving: set[str]
519
+ ) -> None:
520
+ """按日志顺序重放撤销/重做,恢复两个栈的形状。
521
+
522
+ ``surviving`` 是被回退丢弃之后仍成立的回合 id。日志是只追加的:被回退掉的回合
523
+ 的撤销记录还躺在文件里,重放时跳过它们;仍在的回合顺序对不上才算真实损坏。
524
+ """
525
+ for line in lines:
526
+ if not line.strip():
527
+ continue
528
+ try:
529
+ parsed: JsonValue = json.loads(line)
530
+ except json.JSONDecodeError:
531
+ break
532
+ if not isinstance(parsed, dict):
533
+ continue
534
+ record: dict[str, JsonValue] = parsed
535
+ kind = record.get("type")
536
+ if kind == "clear_redo":
537
+ self._redo.clear()
538
+ continue
539
+ if kind not in ("undo", "redo"):
540
+ continue
541
+ turn_id = record.get("turn")
542
+ if not isinstance(turn_id, str) or turn_id not in drafts:
543
+ continue
544
+ if turn_id not in surviving:
545
+ continue
546
+ turn = drafts[turn_id].turn()
547
+ if kind == "undo":
548
+ if not self._undo or self._undo[-1].id != turn.id:
549
+ raise CheckpointError(f"{self._log} 的撤销记录与回合顺序不一致:{turn.id}")
550
+ self._undo.pop()
551
+ self._redo.append(turn)
552
+ else:
553
+ if not self._redo or self._redo[-1].id != turn.id:
554
+ raise CheckpointError(f"{self._log} 的重做记录与回合顺序不一致:{turn.id}")
555
+ self._redo.pop()
556
+ self._undo.append(turn)
557
+
558
+ def _close_open_drafts(self) -> None:
559
+ """把上次进程留下的"开了没合"的回合标成 broken。
560
+
561
+ 撤销只需要 ``before_tree``,所以它照样可用;重做需要一个可信的结束状态,
562
+ 而那个状态从来没有被记录过。
563
+ """
564
+ for index, turn in enumerate(self._turns):
565
+ if turn.status != "open":
566
+ continue
567
+ broken = CheckpointTurn(
568
+ id=turn.id,
569
+ sequence=turn.sequence,
570
+ started_at=turn.started_at,
571
+ before_tree=turn.before_tree,
572
+ after_tree=None,
573
+ status="broken",
574
+ finished_at=None,
575
+ changes=turn.changes,
576
+ message_entry_id=turn.message_entry_id,
577
+ )
578
+ self._turns[index] = broken
579
+ # 中断的回合没有改动清单,但它的起点的可信的:撤销就是"回到那一刻"。
580
+ # 没有可信的结束状态,所以它只能被撤销,不能被重做。
581
+ self._undo.append(broken)
582
+ self._append(
583
+ {
584
+ "type": "turn_end",
585
+ "id": turn.id,
586
+ "afterTree": None,
587
+ "status": "broken",
588
+ "finishedAt": None,
589
+ "changes": [change.to_json() for change in broken.changes],
590
+ }
591
+ )
592
+
593
+ # ------------------------------------------------------------- 回合边界
594
+
595
+ async def begin_turn(self) -> CheckpointTurn:
596
+ """记下回合起点。已有一个打开的回合时直接失败——嵌套回合没有定义好的语义。"""
597
+ await self.ensure_ready()
598
+ async with self._lock:
599
+ if self._draft is not None:
600
+ raise CheckpointError(f"回合 {self._draft.id} 还没结束,不能开启新回合")
601
+ before = await self._capture()
602
+ self._sequence += 1
603
+ draft = _Draft(
604
+ id=f"t{self._sequence}",
605
+ sequence=self._sequence,
606
+ started_at=self._now(),
607
+ before_tree=before,
608
+ )
609
+ self._draft = draft
610
+ self._pending_shell.clear()
611
+ self._append(
612
+ {
613
+ "type": "turn",
614
+ "id": draft.id,
615
+ "sequence": draft.sequence,
616
+ "startedAt": draft.started_at,
617
+ "beforeTree": draft.before_tree,
618
+ }
619
+ )
620
+ return draft.turn()
621
+
622
+ async def end_turn(self) -> CheckpointTurn | None:
623
+ """合上回合,算出改动。没有改动就不进撤销栈。"""
624
+ if self._draft is None:
625
+ return None
626
+ await self.ensure_ready()
627
+ async with self._lock:
628
+ draft = self._draft
629
+ self._draft = None
630
+ self._pending_shell.clear()
631
+ try:
632
+ after = await self._capture()
633
+ changes = await self._collect_changes(draft, after)
634
+ status: TurnStatus = "closed"
635
+ except (CheckpointError, GitError, OSError) as error:
636
+ # 命令已经执行完,副作用已经发生。把这里翻成异常只会让调用方以为
637
+ # 工具失败;记下来,交给 /status 说明。
638
+ logger.warning("检查点:回合 %s 结束快照失败:%s", draft.id, error)
639
+ self._last_error = str(error)
640
+ after = None
641
+ changes = self._changes_from_records(draft)
642
+ status = "broken"
643
+ draft.after_tree = after
644
+ draft.finished_at = self._now()
645
+ draft.status = status
646
+ for change in changes:
647
+ draft.changes[change.path] = change
648
+ turn = draft.turn()
649
+ self._append(
650
+ {
651
+ "type": "turn_end",
652
+ "id": turn.id,
653
+ "afterTree": turn.after_tree,
654
+ "status": turn.status,
655
+ "finishedAt": turn.finished_at,
656
+ "changes": [change.to_json() for change in turn.changes],
657
+ }
658
+ )
659
+ self._turns.append(turn)
660
+ if turn.changes:
661
+ self._undo.append(turn)
662
+ if self._redo:
663
+ self._redo.clear()
664
+ self._append({"type": "clear_redo"})
665
+ return turn
666
+
667
+ # --------------------------------------------------------- 工具前像记录
668
+
669
+ async def bind_message(self, entry_id: str) -> None:
670
+ """把当前打开的回合与发起它的用户消息条目绑定。
671
+
672
+ 只在第一个用户消息上生效:一次回合里后续还可能有 steering 追加的用户消息,
673
+ 回退要回到的是"这个回合从哪一句开始的"。
674
+ """
675
+ async with self._lock:
676
+ draft = self._draft
677
+ if draft is None or draft.message_entry_id is not None:
678
+ return
679
+ draft.message_entry_id = entry_id
680
+ self._append({"type": "turn_bind", "id": draft.id, "messageEntryId": entry_id})
681
+
682
+ def turn_for_message(self, entry_id: str) -> CheckpointTurn | None:
683
+ """发起这个用户消息条目的回合。没有绑定过(或回合被回退丢弃)时返回 ``None``。"""
684
+ for turn in self._turns:
685
+ if turn.message_entry_id == entry_id:
686
+ return turn
687
+ return None
688
+
689
+ async def record_file(self, path: str, signal: CancelToken | None = None) -> None:
690
+ """在 ``write`` / ``edit`` 之前记下目标文件的内容。
691
+
692
+ 工作目录之外的文件也能记:树装不下它,但"路径 → 内容"这一层与前像无关,
693
+ 用绝对路径同样能写回。这样权限引擎批准过的跨目录编辑不会因为检查点被拒。
694
+
695
+ :raises CheckpointError: 文件存在但读不出来。调用方据此拒绝这次工具调用。
696
+ """
697
+ if self._draft is None:
698
+ return
699
+ await self.ensure_ready()
700
+ async with self._lock:
701
+ draft = self._draft
702
+ assert draft is not None
703
+ relative, absolute = self._classify(path)
704
+ recorded = relative if relative is not None else absolute.replace(os.sep, "/")
705
+ if recorded in draft.files:
706
+ return # 同一回合里第二次改同一个文件:第一次的前像才是撤销目标
707
+ if os.path.islink(absolute):
708
+ # 链接不进快照:``git`` 记的是链接目标,写回时会把链接变成普通文件。
709
+ self._skipped = (*self._skipped, SkippedFile(path=recorded, reason="symlink"))
710
+ return
711
+ try:
712
+ data = await asyncio.to_thread(_read_bytes, absolute)
713
+ except FileNotFoundError:
714
+ before = None
715
+ except OSError as error:
716
+ raise CheckpointError(
717
+ f"检查点无法读取 {recorded}:{error};这次改动没有被记录,因此不能撤销"
718
+ ) from error
719
+ else:
720
+ if len(data) > self._settings.max_file_bytes:
721
+ self._skipped = (*self._skipped, SkippedFile(path=recorded, reason="too_large"))
722
+ return
723
+ before = await self._hash_object(data, signal)
724
+ draft.files[recorded] = before
725
+ self._append({"type": "file", "turn": draft.id, "path": recorded, "before": before})
726
+
727
+ # ------------------------------------------------------------ 工具钩子
728
+
729
+ async def before_tool(
730
+ self,
731
+ tool_call_id: str,
732
+ tool_name: str,
733
+ args: dict[str, JsonValue],
734
+ signal: CancelToken | None = None,
735
+ ) -> None:
736
+ """工具执行前:``write`` / ``edit`` 记文件前像,``bash`` 记工作区状态。"""
737
+ if self._draft is None:
738
+ return
739
+ if tool_name in FILE_TOOLS:
740
+ path = args.get("path")
741
+ if isinstance(path, str) and path.strip():
742
+ await self.record_file(path, signal)
743
+ return
744
+ if tool_name not in SHELL_TOOLS:
745
+ return
746
+ await self.ensure_ready()
747
+ async with self._lock:
748
+ try:
749
+ self._pending_shell[tool_call_id] = await self._capture()
750
+ except (GitError, OSError) as error:
751
+ # 命令还没跑,前像丢了只影响"这条命令改了什么"的归属;
752
+ # 回合级的前像仍然在,撤销本身不受影响。
753
+ logger.warning("检查点:bash 前快照失败:%s", error)
754
+ self._last_error = str(error)
755
+
756
+ async def after_tool(
757
+ self,
758
+ tool_call_id: str,
759
+ tool_name: str,
760
+ args: dict[str, JsonValue],
761
+ signal: CancelToken | None = None,
762
+ ) -> None:
763
+ """工具执行后:把 ``bash`` 造成的改动记进当前回合。"""
764
+ del args, signal
765
+ if tool_name not in SHELL_TOOLS:
766
+ return
767
+ before = self._pending_shell.pop(tool_call_id, None)
768
+ if before is None or self._draft is None:
769
+ return
770
+ await self.ensure_ready()
771
+ async with self._lock:
772
+ draft = self._draft
773
+ assert draft is not None
774
+ try:
775
+ after = await self._capture()
776
+ changes = await self._diff_trees(before, after)
777
+ except (GitError, OSError) as error:
778
+ logger.warning("检查点:bash 后快照失败:%s", error)
779
+ self._last_error = str(error)
780
+ return
781
+ draft.shells += 1
782
+ for change in changes:
783
+ draft.changes.setdefault(change.path, change)
784
+ self._append(
785
+ {
786
+ "type": "shell",
787
+ "turn": draft.id,
788
+ "toolCallId": tool_call_id,
789
+ "beforeTree": before,
790
+ "afterTree": after,
791
+ "changes": [change.to_json() for change in changes],
792
+ }
793
+ )
794
+
795
+ # --------------------------------------------------------------- 撤销
796
+
797
+ async def undo(self) -> UndoResult:
798
+ """恢复最近一次有改动的回合之前的文件状态。"""
799
+ await self.ensure_ready()
800
+ async with self._lock:
801
+ if not self._undo:
802
+ return UndoResult(
803
+ applied=False,
804
+ message="没有可撤销的回合:本次会话还没有改过文件",
805
+ undo_depth=0,
806
+ redo_depth=len(self._redo),
807
+ )
808
+ turn = self._undo.pop()
809
+ changes = await self._restore(turn.before_tree, turn)
810
+ self._redo.append(turn)
811
+ self._append({"type": "undo", "turn": turn.id, "at": self._now()})
812
+ return UndoResult(
813
+ applied=True,
814
+ message=f"已撤销{turn.summary()}",
815
+ turn=turn,
816
+ changes=changes,
817
+ undo_depth=len(self._undo),
818
+ redo_depth=len(self._redo),
819
+ )
820
+
821
+ async def redo(self) -> UndoResult:
822
+ """重新应用最近一次被撤销的回合。"""
823
+ await self.ensure_ready()
824
+ async with self._lock:
825
+ if not self._redo:
826
+ return UndoResult(
827
+ applied=False,
828
+ message="没有可重做的回合:撤销之后还没有新的改动",
829
+ undo_depth=len(self._undo),
830
+ redo_depth=0,
831
+ )
832
+ turn = self._redo.pop()
833
+ if turn.after_tree is None:
834
+ self._undo.append(turn)
835
+ return UndoResult(
836
+ applied=False,
837
+ message=(
838
+ f"第 {turn.sequence} 回合结束时进程中断,没有记录结束状态,无法重做;"
839
+ "文件保持现状"
840
+ ),
841
+ turn=turn,
842
+ undo_depth=len(self._undo),
843
+ redo_depth=len(self._redo),
844
+ )
845
+ changes = await self._restore(turn.after_tree, turn, reverse=True)
846
+ self._undo.append(turn)
847
+ self._append({"type": "redo", "turn": turn.id, "at": self._now()})
848
+ return UndoResult(
849
+ applied=True,
850
+ message=f"已重做{turn.summary()}",
851
+ turn=turn,
852
+ changes=changes,
853
+ undo_depth=len(self._undo),
854
+ redo_depth=len(self._redo),
855
+ )
856
+
857
+ # ---------------------------------------------------------------- 差异
858
+
859
+ async def diff(self, *, max_lines: int = 0) -> SessionDiff:
860
+ """会话基线 → 当前工作区的差异。``max_lines`` 为 0 表示不截断。"""
861
+ await self.ensure_ready()
862
+ async with self._lock:
863
+ assert self._baseline is not None
864
+ current = await self._capture()
865
+ changes = await self._diff_trees(self._baseline, current)
866
+ patch = ""
867
+ if changes:
868
+ patch = await self._git.out("diff", "--no-color", self._baseline, current, "--")
869
+ lines = patch.splitlines()
870
+ truncated = bool(max_lines) and len(lines) > max_lines
871
+ if truncated:
872
+ patch = "\n".join(lines[:max_lines])
873
+ return SessionDiff(
874
+ baseline_tree=self._baseline,
875
+ current_tree=current,
876
+ changes=changes,
877
+ patch=patch,
878
+ truncated=truncated,
879
+ )
880
+
881
+ async def capture(self) -> str:
882
+ """抓一次工作区快照,返回树哈希。"""
883
+ await self.ensure_ready()
884
+ async with self._lock:
885
+ return await self._capture()
886
+
887
+ async def changes_to(self, tree: str) -> tuple[FileChange, ...]:
888
+ """当前工作区 → ``tree`` 的文件改动。回退前的确认清单用它。
889
+
890
+ 方向是"恢复到那棵树会做什么":``added`` 表示这个文件会被创建,``deleted``
891
+ 表示会被删除,``modified`` 表示会被改写。用户看到的清单应当是动作,而不是
892
+ "这些文件在树里是什么状态"。
893
+ """
894
+ await self.ensure_ready()
895
+ async with self._lock:
896
+ current = await self._capture()
897
+ if current == tree:
898
+ return ()
899
+ return await self._diff_trees(current, tree)
900
+
901
+ async def restore_to(self, tree: str) -> tuple[FileChange, ...]:
902
+ """把整个工作区恢复成 ``tree``,返回被改动的文件。
903
+
904
+ 与 :meth:`undo` 的差别是范围:``undo`` 只碰那一个回合改过的路径,``restore_to``
905
+ 做整树恢复,会删掉这棵树之后新增的文件。那是"回到过去"的语义,因此调用方必须
906
+ 先把 :meth:`changes_to` 的结果给用户看过。
907
+ """
908
+ await self.ensure_ready()
909
+ async with self._lock:
910
+ return await self._restore_tree(tree)
911
+
912
+ async def truncate_from(self, sequence: int) -> None:
913
+ """丢弃 ``sequence`` 及之后的回合,并把这次截断写进日志。
914
+
915
+ 回退之后这些回合的起点与终点都不再是工作区的事实。留着它们,下一次
916
+ ``/undo`` 会把用户刚退回去的改动又"撤销"一遍,方向正好相反。
917
+
918
+ :raises CheckpointError: 当前还开着一个回合(运行中不能截断历史)。
919
+ """
920
+ if self._draft is not None:
921
+ raise CheckpointError(f"回合 {self._draft.id} 还没结束,不能截断回合记录")
922
+ async with self._lock:
923
+ self._turns = [turn for turn in self._turns if turn.sequence < sequence]
924
+ self._undo = [turn for turn in self._undo if turn.sequence < sequence]
925
+ self._redo.clear()
926
+ self._append({"type": "rewind", "toSequence": sequence, "at": self._now()})
927
+
928
+ async def list_tree(self, tree: str) -> tuple[str, ...]:
929
+ """一棵树里的全部路径(相对工作目录,posix 写法)。"""
930
+ raw = await self._git.run("ls-tree", "-r", "-z", "--name-only", tree)
931
+ if not raw.ok:
932
+ raise CheckpointError(
933
+ f"读取快照树失败({tree}):{raw.error_text.strip() or raw.text.strip()}"
934
+ )
935
+ return tuple(os.fsdecode(chunk) for chunk in raw.content.split(b"\0") if chunk)
936
+
937
+ # ------------------------------------------------------------- 内部实现
938
+
939
+ def _now(self) -> str:
940
+ return iso_from_ms(self._clock.now_ms())
941
+
942
+ def _append(self, record: dict[str, JsonValue]) -> None:
943
+ """追加一行日志并落盘。检查点日志丢了就等于撤销历史丢了。"""
944
+ os.makedirs(self._repo, exist_ok=True)
945
+ with open(self._log, "a", encoding="utf-8", newline="\n") as handle:
946
+ handle.write(json.dumps(record, ensure_ascii=False) + "\n")
947
+ handle.flush()
948
+ os.fsync(handle.fileno())
949
+
950
+ def _classify(self, path: str) -> tuple[str | None, str]:
951
+ """工具给的路径 → (相对工作目录的 posix 路径, 绝对路径)。
952
+
953
+ 相对路径返回 ``None`` 表示它落在工作目录之外:树装不下它。
954
+ """
955
+ absolute = os.path.abspath(path if os.path.isabs(path) else os.path.join(self._cwd, path))
956
+ relative = os.path.relpath(absolute, self._cwd)
957
+ if relative == ".." or relative.startswith(".." + os.sep):
958
+ return None, absolute
959
+ return relative.replace(os.sep, "/"), absolute
960
+
961
+ async def _capture(self) -> str:
962
+ """把工作区写进树,返回树哈希。
963
+
964
+ 三步:列出候选(跟随 ``.gitignore`` 与本仓库的 ``info/exclude``)→ 过滤掉
965
+ 符号链接、硬链接、超大文件与被排除的目录 → 分两条命令更新索引(删除消失的、
966
+ 加入留下的)。
967
+
968
+ 被排除的目录(影子仓库自己、会话目录)里的路径要从索引里摘掉,而不只是跳过:
969
+ ``info/exclude`` 只管未跟踪的文件,上一版实现抓进去的路径仍然留在索引里,
970
+ 只跳过不删除的话它们照样会出现在树上。
971
+ """
972
+ candidates = await self._list_candidates()
973
+ prefixes = self._excluded_prefixes()
974
+ excluded = [
975
+ path for path in candidates if any(path.startswith(prefix) for prefix in prefixes)
976
+ ]
977
+ if excluded:
978
+ await self._remove_from_index(excluded)
979
+ excluded_set = set(excluded)
980
+ candidates = [path for path in candidates if path not in excluded_set]
981
+ keep: list[str] = []
982
+ stale: list[str] = []
983
+ skipped: list[SkippedFile] = []
984
+ for relative in candidates:
985
+ absolute = os.path.join(self._cwd, relative)
986
+ try:
987
+ info = os.lstat(absolute)
988
+ except FileNotFoundError:
989
+ stale.append(relative)
990
+ continue
991
+ if stat.S_ISLNK(info.st_mode):
992
+ skipped.append(SkippedFile(path=relative, reason="symlink"))
993
+ stale.append(relative)
994
+ continue
995
+ if info.st_nlink > 1:
996
+ skipped.append(SkippedFile(path=relative, reason="hardlink"))
997
+ stale.append(relative)
998
+ continue
999
+ if info.st_size > self._settings.max_file_bytes:
1000
+ skipped.append(SkippedFile(path=relative, reason="too_large"))
1001
+ stale.append(relative)
1002
+ continue
1003
+ # 读不到的文件直接跳过:``git add`` 是整批失败,一个 0600 的别人的文件
1004
+ # 会让整次快照失败,进而让每个回合的起点都抓不到。
1005
+ if not os.access(absolute, os.R_OK):
1006
+ skipped.append(SkippedFile(path=relative, reason="unreadable"))
1007
+ stale.append(relative)
1008
+ continue
1009
+ keep.append(relative)
1010
+ self._skipped = tuple(skipped)
1011
+ if stale:
1012
+ await self._remove_from_index(stale)
1013
+ if keep:
1014
+ await self._stage(keep)
1015
+ tree = await self._git.out("write-tree")
1016
+ return tree
1017
+
1018
+ async def _list_candidates(self) -> list[str]:
1019
+ raw = await self._git.run("ls-files", "-z", "--cached", "--others", "--exclude-standard")
1020
+ if not raw.ok:
1021
+ raise CheckpointError(
1022
+ f"检查点无法列出工作区文件:{raw.error_text.strip() or raw.text.strip()}"
1023
+ )
1024
+ return [os.fsdecode(chunk) for chunk in raw.content.split(b"\0") if chunk]
1025
+
1026
+ async def _remove_from_index(self, paths: Sequence[str]) -> None:
1027
+ stdin = b"".join(os.fsencode(path) + b"\0" for path in paths)
1028
+ await self._git.out(
1029
+ "rm",
1030
+ "--cached",
1031
+ "--ignore-unmatch",
1032
+ "-q",
1033
+ "--pathspec-from-file=-",
1034
+ "--pathspec-file-nul",
1035
+ stdin=stdin,
1036
+ )
1037
+
1038
+ async def _stage(self, paths: Sequence[str]) -> None:
1039
+ stdin = b"".join(os.fsencode(path) + b"\0" for path in paths)
1040
+ await self._git.out("add", "--pathspec-from-file=-", "--pathspec-file-nul", stdin=stdin)
1041
+
1042
+ async def _hash_object(self, data: bytes, signal: CancelToken | None) -> str:
1043
+ return await self._git.out("hash-object", "-w", "--stdin", stdin=data, signal=signal)
1044
+
1045
+ async def _read_blob(self, blob: str) -> bytes:
1046
+ result = await self._git.run("cat-file", "blob", blob)
1047
+ if not result.ok:
1048
+ raise CheckpointError(
1049
+ f"读取快照内容失败({blob}):{result.error_text.strip() or result.text.strip()}"
1050
+ )
1051
+ return result.content
1052
+
1053
+ async def _diff_trees(self, before: str, after: str) -> tuple[FileChange, ...]:
1054
+ """两棵树之间的文件级差异。顺序按路径排序,输出稳定。"""
1055
+ if before == after:
1056
+ return ()
1057
+ raw = await self._git.run("diff", "--name-status", "-z", before, after, "--")
1058
+ if not raw.ok:
1059
+ raise CheckpointError(f"比较快照失败:{raw.error_text.strip() or raw.text.strip()}")
1060
+ fields = [os.fsdecode(chunk) for chunk in raw.content.split(b"\0") if chunk]
1061
+ changes: dict[str, FileChange] = {}
1062
+ index = 0
1063
+ while index + 1 < len(fields):
1064
+ code = fields[index]
1065
+ path = fields[index + 1]
1066
+ index += 2
1067
+ if code.startswith("D"):
1068
+ status: ChangeStatus = "deleted"
1069
+ elif code.startswith("A"):
1070
+ status = "added"
1071
+ else:
1072
+ status = "modified"
1073
+ changes[path] = FileChange(
1074
+ path=path,
1075
+ status=status,
1076
+ before=await self._blob_at(before, path),
1077
+ after=await self._blob_at(after, path),
1078
+ )
1079
+ return tuple(changes[path] for path in sorted(changes))
1080
+
1081
+ async def _blob_at(self, tree: str, path: str) -> str | None:
1082
+ raw = await self._git.run("ls-tree", "-z", tree, "--", path)
1083
+ if not raw.ok:
1084
+ raise CheckpointError(
1085
+ f"读取快照条目失败({tree}:{path}):{raw.error_text.strip() or raw.text.strip()}"
1086
+ )
1087
+ text = raw.content.decode("utf-8", errors="replace")
1088
+ if not text.strip():
1089
+ return None
1090
+ # 形状:``<mode> <type> <hash>\t<path>\0``
1091
+ head, _, _ = text.partition("\t")
1092
+ parts = head.split()
1093
+ return parts[2] if len(parts) >= 3 else None
1094
+
1095
+ async def _collect_changes(self, draft: _Draft, after: str) -> tuple[FileChange, ...]:
1096
+ """回合改动 = 树差异 + 树看不见的被忽略文件。"""
1097
+ tree_changes = await self._diff_trees(draft.before_tree, after)
1098
+ covered = {change.path for change in tree_changes}
1099
+ merged: dict[str, FileChange] = {change.path: change for change in tree_changes}
1100
+ for path, before in sorted(draft.files.items()):
1101
+ if path in covered:
1102
+ continue
1103
+ after_blob = await self._hash_path(path)
1104
+ if before == after_blob:
1105
+ continue
1106
+ status: ChangeStatus = (
1107
+ "added" if before is None else "deleted" if after_blob is None else "modified"
1108
+ )
1109
+ merged[path] = FileChange(
1110
+ path=path,
1111
+ status=status,
1112
+ before=before,
1113
+ after=after_blob,
1114
+ source="file",
1115
+ )
1116
+ return tuple(merged[path] for path in sorted(merged))
1117
+
1118
+ def _changes_from_records(self, draft: _Draft) -> tuple[FileChange, ...]:
1119
+ """快照失败时的退路:用已经记下的命令与文件记录拼出改动清单。"""
1120
+ merged = dict(draft.changes)
1121
+ for path, before in sorted(draft.files.items()):
1122
+ merged.setdefault(
1123
+ path,
1124
+ FileChange(
1125
+ path=path,
1126
+ status="modified",
1127
+ before=before,
1128
+ after=None,
1129
+ source="file",
1130
+ ),
1131
+ )
1132
+ return tuple(merged[path] for path in sorted(merged))
1133
+
1134
+ async def _hash_path(self, path: str) -> str | None:
1135
+ absolute = os.path.join(self._cwd, path)
1136
+ try:
1137
+ data = await asyncio.to_thread(_read_bytes, absolute)
1138
+ except FileNotFoundError:
1139
+ return None
1140
+ return await self._hash_object(data, None)
1141
+
1142
+ async def _restore(
1143
+ self,
1144
+ target: str,
1145
+ turn: CheckpointTurn,
1146
+ *,
1147
+ reverse: bool = False,
1148
+ ) -> tuple[FileChange, ...]:
1149
+ """把这一回合改动过的文件恢复成 ``target`` 那棵树里的样子。
1150
+
1151
+ 只碰 ``turn.changes`` 里的路径,不做整树覆盖。整树覆盖会把"这一回合之后
1152
+ 别的进程新建的文件"也删掉——两个会话同时改一个仓库时,一次撤销会顺手抹掉
1153
+ 另一个会话的成果。撤销属于"改回去",不属于"回到过去"。
1154
+
1155
+ 例外是**没有改动清单的中断回合**:进程死在半路,我们只知道起点树。那时
1156
+ 按整棵树恢复(:meth:`_restore_tree`),否则撤销什么都不会发生。
1157
+ """
1158
+ if not turn.changes:
1159
+ return await self._restore_tree(target)
1160
+ restored: list[FileChange] = []
1161
+ tree_changes = [change for change in turn.changes if change.source == "tree"]
1162
+ if tree_changes:
1163
+ await self._git.out("read-tree", target)
1164
+ writes: list[str] = []
1165
+ for change in tree_changes:
1166
+ blob = change.after if reverse else change.before
1167
+ absolute = os.path.join(self._cwd, change.path)
1168
+ if blob is None:
1169
+ if os.path.lexists(absolute):
1170
+ await asyncio.to_thread(_remove_file, absolute)
1171
+ else:
1172
+ writes.append(change.path)
1173
+ restored.append(change)
1174
+ for start in range(0, len(writes), _CHECKOUT_BATCH):
1175
+ batch = writes[start : start + _CHECKOUT_BATCH]
1176
+ await self._git.out("checkout-index", "-f", "--", *batch)
1177
+ await self._restore_file_records(turn, reverse=reverse)
1178
+ return tuple(restored) + tuple(change for change in turn.changes if change.source == "file")
1179
+
1180
+ async def _restore_tree(self, target: str) -> tuple[FileChange, ...]:
1181
+ """整树恢复:唯一给"没有改动清单"的中断回合用的路径。"""
1182
+ current = await self._capture()
1183
+ if current == target:
1184
+ return ()
1185
+ changes = await self._diff_trees(current, target)
1186
+ # 这一轮抓取里被跳过的路径(符号链接、硬链接、超大文件)绝不能被"恢复"
1187
+ # 顺手删掉:它们不在树里,不代表它们不该存在。
1188
+ protected = {item.path for item in self._skipped}
1189
+ removals = [
1190
+ change.path
1191
+ for change in changes
1192
+ if change.status == "deleted" and change.path not in protected
1193
+ ]
1194
+ for path in removals:
1195
+ absolute = os.path.join(self._cwd, path)
1196
+ if os.path.lexists(absolute):
1197
+ await asyncio.to_thread(_remove_file, absolute)
1198
+ await self._git.out("read-tree", target)
1199
+ writes = [
1200
+ change.path
1201
+ for change in changes
1202
+ if change.status != "deleted" and change.path not in protected
1203
+ ]
1204
+ for start in range(0, len(writes), _CHECKOUT_BATCH):
1205
+ batch = writes[start : start + _CHECKOUT_BATCH]
1206
+ await self._git.out("checkout-index", "-f", "--", *batch)
1207
+ return changes
1208
+
1209
+ async def _restore_file_records(self, turn: CheckpointTurn, *, reverse: bool) -> None:
1210
+ """被 ``.gitignore`` 排除的文件不在树里,只能按前像逐个写回。"""
1211
+ for change in turn.changes:
1212
+ if change.source != "file":
1213
+ continue
1214
+ blob = change.after if reverse else change.before
1215
+ absolute = os.path.join(self._cwd, change.path)
1216
+ if blob is None:
1217
+ if os.path.lexists(absolute):
1218
+ await asyncio.to_thread(_remove_file, absolute)
1219
+ continue
1220
+ data = await self._read_blob(blob)
1221
+ parent = os.path.dirname(absolute)
1222
+ if parent:
1223
+ os.makedirs(parent, exist_ok=True)
1224
+ await asyncio.to_thread(_write_bytes, absolute, data)
1225
+
1226
+
1227
+ def _read_bytes(path: str) -> bytes:
1228
+ with open(path, "rb") as handle:
1229
+ return handle.read()
1230
+
1231
+
1232
+ def _write_bytes(path: str, data: bytes) -> None:
1233
+ with open(path, "wb") as handle:
1234
+ handle.write(data)
1235
+
1236
+
1237
+ def _remove_file(path: str) -> None:
1238
+ os.remove(path)
1239
+
1240
+
1241
+ __all__ = [
1242
+ "DEFAULT_MAX_FILE_BYTES",
1243
+ "FILE_TOOLS",
1244
+ "LOG_NAME",
1245
+ "LOG_VERSION",
1246
+ "SHELL_TOOLS",
1247
+ "SNAPSHOTS_DIR",
1248
+ "ChangeSource",
1249
+ "ChangeStatus",
1250
+ "CheckpointError",
1251
+ "CheckpointSettings",
1252
+ "CheckpointStatus",
1253
+ "CheckpointStore",
1254
+ "CheckpointTurn",
1255
+ "FileChange",
1256
+ "SessionDiff",
1257
+ "SkipReason",
1258
+ "SkippedFile",
1259
+ "TurnStatus",
1260
+ "UndoResult",
1261
+ ]