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.
- braid_coding_agent/__init__.py +13 -0
- braid_coding_agent/assembly.py +460 -0
- braid_coding_agent/cancellation.py +25 -0
- braid_coding_agent/checkpoint/__init__.py +106 -0
- braid_coding_agent/checkpoint/git.py +305 -0
- braid_coding_agent/checkpoint/settings.py +26 -0
- braid_coding_agent/checkpoint/store.py +1261 -0
- braid_coding_agent/checkpoint/workspace.py +220 -0
- braid_coding_agent/cli.py +2168 -0
- braid_coding_agent/commands/__init__.py +50 -0
- braid_coding_agent/commands/auth.py +161 -0
- braid_coding_agent/commands/config.py +180 -0
- braid_coding_agent/commands/doctor.py +511 -0
- braid_coding_agent/commands/mcp.py +928 -0
- braid_coding_agent/commands/models.py +95 -0
- braid_coding_agent/commands/setup.py +89 -0
- braid_coding_agent/commands/uninstall.py +277 -0
- braid_coding_agent/commands/upgrade.py +381 -0
- braid_coding_agent/compaction/__init__.py +174 -0
- braid_coding_agent/compaction/prepare.py +430 -0
- braid_coding_agent/compaction/summarize.py +542 -0
- braid_coding_agent/compaction/tokens.py +204 -0
- braid_coding_agent/compaction/tool_results.py +196 -0
- braid_coding_agent/compaction/utils.py +181 -0
- braid_coding_agent/config.py +2776 -0
- braid_coding_agent/config_files.py +191 -0
- braid_coding_agent/credentials.py +252 -0
- braid_coding_agent/discovery.py +415 -0
- braid_coding_agent/extensions/__init__.py +77 -0
- braid_coding_agent/extensions/api.py +480 -0
- braid_coding_agent/extensions/runner.py +553 -0
- braid_coding_agent/formatting/__init__.py +62 -0
- braid_coding_agent/formatting/settings.py +87 -0
- braid_coding_agent/formatting/tool.py +179 -0
- braid_coding_agent/lsp/__init__.py +105 -0
- braid_coding_agent/lsp/client.py +546 -0
- braid_coding_agent/lsp/manager.py +187 -0
- braid_coding_agent/lsp/model.py +316 -0
- braid_coding_agent/lsp/protocol.py +105 -0
- braid_coding_agent/lsp/settings.py +120 -0
- braid_coding_agent/lsp/tool.py +429 -0
- braid_coding_agent/mcp/__init__.py +101 -0
- braid_coding_agent/mcp/cache.py +230 -0
- braid_coding_agent/mcp/catalog.py +108 -0
- braid_coding_agent/mcp/config.py +664 -0
- braid_coding_agent/mcp/config_store.py +142 -0
- braid_coding_agent/mcp/inspector.py +85 -0
- braid_coding_agent/mcp/panel.py +254 -0
- braid_coding_agent/mcp/runtime.py +1060 -0
- braid_coding_agent/mcp/tools.py +579 -0
- braid_coding_agent/mcp/trust.py +150 -0
- braid_coding_agent/mcp/tui_panel.py +444 -0
- braid_coding_agent/messages.py +152 -0
- braid_coding_agent/models_view.py +105 -0
- braid_coding_agent/modes/__init__.py +64 -0
- braid_coding_agent/modes/json_mode.py +480 -0
- braid_coding_agent/modes/lifecycle.py +217 -0
- braid_coding_agent/modes/print_mode.py +257 -0
- braid_coding_agent/modes/repl.py +2687 -0
- braid_coding_agent/modes/repl_commands.py +263 -0
- braid_coding_agent/modes/rpc.py +953 -0
- braid_coding_agent/modes/skill_commands.py +88 -0
- braid_coding_agent/modes/tui.py +2226 -0
- braid_coding_agent/modes/tui_control.py +90 -0
- braid_coding_agent/modes/tui_model.py +1043 -0
- braid_coding_agent/modes/tui_render.py +327 -0
- braid_coding_agent/modes/tui_rich.py +751 -0
- braid_coding_agent/modes/tui_style.py +42 -0
- braid_coding_agent/modes/wire.py +81 -0
- braid_coding_agent/netsafe.py +82 -0
- braid_coding_agent/network/__init__.py +20 -0
- braid_coding_agent/network/cache.py +77 -0
- braid_coding_agent/network/fetch.py +311 -0
- braid_coding_agent/network/html_text.py +160 -0
- braid_coding_agent/network/search.py +347 -0
- braid_coding_agent/network/settings.py +103 -0
- braid_coding_agent/network/urls.py +89 -0
- braid_coding_agent/observability/__init__.py +101 -0
- braid_coding_agent/observability/audit.py +124 -0
- braid_coding_agent/observability/collector.py +314 -0
- braid_coding_agent/observability/exporter.py +74 -0
- braid_coding_agent/observability/logging_setup.py +149 -0
- braid_coding_agent/observability/redaction.py +96 -0
- braid_coding_agent/observability/settings.py +29 -0
- braid_coding_agent/observability/spans.py +239 -0
- braid_coding_agent/permissions/__init__.py +185 -0
- braid_coding_agent/permissions/command.py +586 -0
- braid_coding_agent/permissions/engine.py +522 -0
- braid_coding_agent/permissions/evaluate.py +309 -0
- braid_coding_agent/permissions/matching.py +233 -0
- braid_coding_agent/permissions/model.py +278 -0
- braid_coding_agent/permissions/policy.py +99 -0
- braid_coding_agent/permissions/readonly.py +236 -0
- braid_coding_agent/permissions/store.py +379 -0
- braid_coding_agent/project_init.py +313 -0
- braid_coding_agent/prompt/__init__.py +98 -0
- braid_coding_agent/prompt/context_files.py +253 -0
- braid_coding_agent/prompt/project_context.py +172 -0
- braid_coding_agent/prompt/system_prompt.py +378 -0
- braid_coding_agent/questions.py +71 -0
- braid_coding_agent/render/__init__.py +56 -0
- braid_coding_agent/render/batch.py +66 -0
- braid_coding_agent/render/history.py +143 -0
- braid_coding_agent/render/stream.py +823 -0
- braid_coding_agent/render/theme.py +243 -0
- braid_coding_agent/sandbox/__init__.py +89 -0
- braid_coding_agent/sandbox/backend.py +184 -0
- braid_coding_agent/sandbox/bubblewrap.py +96 -0
- braid_coding_agent/sandbox/operations.py +301 -0
- braid_coding_agent/sandbox/policy.py +221 -0
- braid_coding_agent/sandbox/proxy.py +320 -0
- braid_coding_agent/sandbox/seatbelt.py +222 -0
- braid_coding_agent/sdk/__init__.py +31 -0
- braid_coding_agent/sdk/async_client.py +366 -0
- braid_coding_agent/sdk/client.py +386 -0
- braid_coding_agent/sdk/errors.py +52 -0
- braid_coding_agent/sdk/events.py +162 -0
- braid_coding_agent/sdk/types.py +63 -0
- braid_coding_agent/sdk/wire.py +59 -0
- braid_coding_agent/server/__init__.py +54 -0
- braid_coding_agent/server/errors.py +52 -0
- braid_coding_agent/server/http_server.py +419 -0
- braid_coding_agent/server/hub.py +530 -0
- braid_coding_agent/server/openapi.py +157 -0
- braid_coding_agent/server/registry.py +354 -0
- braid_coding_agent/server/router.py +275 -0
- braid_coding_agent/server/run.py +148 -0
- braid_coding_agent/server/schema.py +194 -0
- braid_coding_agent/server/service.py +975 -0
- braid_coding_agent/session/__init__.py +293 -0
- braid_coding_agent/session/agent_session.py +2706 -0
- braid_coding_agent/session/context_breakdown.py +302 -0
- braid_coding_agent/session/discovery.py +212 -0
- braid_coding_agent/session/entries.py +809 -0
- braid_coding_agent/session/evidence.py +295 -0
- braid_coding_agent/session/lock.py +176 -0
- braid_coding_agent/session/manager.py +1185 -0
- braid_coding_agent/session/plan.py +243 -0
- braid_coding_agent/session/plan_mode.py +423 -0
- braid_coding_agent/session/projection.py +262 -0
- braid_coding_agent/session/rewind.py +257 -0
- braid_coding_agent/session/status.py +240 -0
- braid_coding_agent/settings.py +94 -0
- braid_coding_agent/skills/__init__.py +70 -0
- braid_coding_agent/skills/loader.py +681 -0
- braid_coding_agent/startup/__init__.py +76 -0
- braid_coding_agent/startup/cache.py +72 -0
- braid_coding_agent/startup/diagnostics.py +37 -0
- braid_coding_agent/startup/monitor.py +245 -0
- braid_coding_agent/startup/phases.py +79 -0
- braid_coding_agent/startup/project.py +165 -0
- braid_coding_agent/startup/report.py +560 -0
- braid_coding_agent/startup/scheduler.py +347 -0
- braid_coding_agent/statusline.py +163 -0
- braid_coding_agent/subagents/__init__.py +22 -0
- braid_coding_agent/subagents/contract.py +75 -0
- braid_coding_agent/subagents/definitions.py +583 -0
- braid_coding_agent/subagents/registry.py +277 -0
- braid_coding_agent/subagents/runtime.py +610 -0
- braid_coding_agent/subagents/settings.py +156 -0
- braid_coding_agent/subagents/worktree.py +63 -0
- braid_coding_agent/tools/__init__.py +327 -0
- braid_coding_agent/tools/args.py +87 -0
- braid_coding_agent/tools/bash.py +359 -0
- braid_coding_agent/tools/edit.py +298 -0
- braid_coding_agent/tools/edit_diff.py +344 -0
- braid_coding_agent/tools/find.py +158 -0
- braid_coding_agent/tools/grep.py +305 -0
- braid_coding_agent/tools/ignore.py +198 -0
- braid_coding_agent/tools/ls.py +127 -0
- braid_coding_agent/tools/mutation_queue.py +90 -0
- braid_coding_agent/tools/operations.py +274 -0
- braid_coding_agent/tools/output_accumulator.py +282 -0
- braid_coding_agent/tools/output_store.py +244 -0
- braid_coding_agent/tools/path_utils.py +91 -0
- braid_coding_agent/tools/plan.py +141 -0
- braid_coding_agent/tools/prompt_notes.py +52 -0
- braid_coding_agent/tools/question.py +180 -0
- braid_coding_agent/tools/read.py +223 -0
- braid_coding_agent/tools/submit_plan.py +102 -0
- braid_coding_agent/tools/truncate.py +423 -0
- braid_coding_agent/tools/write.py +100 -0
- braid_coding_agent/untrusted.py +50 -0
- braid_coding_agent/verify/__init__.py +78 -0
- braid_coding_agent/verify/runner.py +260 -0
- braid_coding_agent/verify/settings.py +64 -0
- braid_coding_agent/verify/tool.py +143 -0
- braid_coding_agent-0.1.0.dist-info/METADATA +19 -0
- braid_coding_agent-0.1.0.dist-info/RECORD +192 -0
- braid_coding_agent-0.1.0.dist-info/WHEEL +4 -0
- braid_coding_agent-0.1.0.dist-info/entry_points.txt +3 -0
- braid_coding_agent-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,295 @@
|
|
|
1
|
+
"""完成证据:这一轮 run 改了什么、有没有跑过验证。
|
|
2
|
+
|
|
3
|
+
存在的理由是一条产品规则:**"测试通过"必须是跑出来的,不是写出来的**。模型很容易在
|
|
4
|
+
没有执行任何命令的情况下写出"全部测试通过",而用户从事件流里分不出这句话是观察还是
|
|
5
|
+
声明。会话层因此记录两件事,并在 run 收尾时检查它们是否配套:
|
|
6
|
+
|
|
7
|
+
- **改动**:``write`` / ``edit`` 成功返回,说明文件真的动了;
|
|
8
|
+
- **验证**:``bash`` 执行了一条看起来是"跑检查"的命令(测试、构建、类型检查、lint)。
|
|
9
|
+
|
|
10
|
+
两者都在工具事件里,不需要模型自报。``ToolExecutionStartEvent`` 带参数(路径、命令),
|
|
11
|
+
``ToolExecutionEndEvent`` 带成败,按 ``tool_call_id`` 配对即可——一条失败的命令不算
|
|
12
|
+
改动,也不该被当成"没验证"。
|
|
13
|
+
|
|
14
|
+
## 什么算验证命令
|
|
15
|
+
|
|
16
|
+
判定只做**保守匹配**:宁可漏判(多问模型一次),也不要把 ``grep pytest README.md``
|
|
17
|
+
当成跑过测试。规则是"可执行文件在命令位置上、且属于已知的验证工具":
|
|
18
|
+
|
|
19
|
+
- ``pytest`` / ``mypy`` / ``ruff`` / ``tsc`` 这类工具直接出现在命令位置;
|
|
20
|
+
- ``python -m pytest``:解释器加 ``-m`` 加已知模块;
|
|
21
|
+
- ``npm test`` / ``make verify`` / ``go test`` / ``cargo clippy`` 这类"管理器 + 子命令";
|
|
22
|
+
- 上面任意一种被包在 ``uv run``、``poetry run``、``sudo``、``env``、``bash -c`` 里。
|
|
23
|
+
|
|
24
|
+
命令行按 ``&&``、``||``、``;``、``|`` 与换行切成段,任一段命中即算验证。这条规则的
|
|
25
|
+
代价是:自定义脚本(``./scripts/check.sh``)不会被识别,模型会收到一次提醒,然后在
|
|
26
|
+
提醒里说明它跑的是什么。
|
|
27
|
+
|
|
28
|
+
``verify`` 工具是另一条路:它在配置里声明了"哪些命令算验证",只要被调用过就算跑过
|
|
29
|
+
检查,与那条命令自己的退出码无关——报告失败同样是一次验证,模型已经拿到了结论。
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
from __future__ import annotations
|
|
33
|
+
|
|
34
|
+
import re
|
|
35
|
+
import shlex
|
|
36
|
+
from dataclasses import dataclass, field
|
|
37
|
+
|
|
38
|
+
from braid_ai.types import JsonValue
|
|
39
|
+
|
|
40
|
+
#: 直接以验证工具身份出现的可执行文件名。
|
|
41
|
+
_VERIFICATION_TOOLS: frozenset[str] = frozenset(
|
|
42
|
+
{
|
|
43
|
+
"pytest",
|
|
44
|
+
"py.test",
|
|
45
|
+
"tox",
|
|
46
|
+
"nox",
|
|
47
|
+
"mypy",
|
|
48
|
+
"pyright",
|
|
49
|
+
"ruff",
|
|
50
|
+
"tsc",
|
|
51
|
+
"eslint",
|
|
52
|
+
"biome",
|
|
53
|
+
"jest",
|
|
54
|
+
"vitest",
|
|
55
|
+
"phpunit",
|
|
56
|
+
"rspec",
|
|
57
|
+
"bats",
|
|
58
|
+
"ctest",
|
|
59
|
+
"gotestsum",
|
|
60
|
+
"swift",
|
|
61
|
+
"mix",
|
|
62
|
+
"phpstan",
|
|
63
|
+
"golangci-lint",
|
|
64
|
+
"staticcheck",
|
|
65
|
+
"hadolint",
|
|
66
|
+
"shellcheck",
|
|
67
|
+
}
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
#: ``python -m <模块>`` 里算验证的模块名。
|
|
71
|
+
_VERIFICATION_MODULES: frozenset[str] = frozenset(
|
|
72
|
+
{"pytest", "unittest", "mypy", "ruff", "pyright", "tox", "nox", "compileall"}
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
#: "管理器 + 子命令"里的子命令。``run`` 后面还要再看一层。
|
|
76
|
+
_MANAGER_COMMANDS: dict[str, frozenset[str]] = {
|
|
77
|
+
"npm": frozenset({"test", "t"}),
|
|
78
|
+
"pnpm": frozenset({"test", "t"}),
|
|
79
|
+
"yarn": frozenset({"test", "t"}),
|
|
80
|
+
"bun": frozenset({"test", "t"}),
|
|
81
|
+
"make": frozenset({"test", "check", "verify", "lint"}),
|
|
82
|
+
"just": frozenset({"test", "check", "verify", "lint", "ci"}),
|
|
83
|
+
"go": frozenset({"test", "vet"}),
|
|
84
|
+
"cargo": frozenset({"test", "check", "clippy"}),
|
|
85
|
+
"dotnet": frozenset({"test", "build"}),
|
|
86
|
+
"mvn": frozenset({"test", "verify"}),
|
|
87
|
+
"gradle": frozenset({"test", "check"}),
|
|
88
|
+
"gradlew": frozenset({"test", "check"}),
|
|
89
|
+
"rake": frozenset({"test", "spec"}),
|
|
90
|
+
"swift": frozenset({"test"}),
|
|
91
|
+
"zig": frozenset({"build"}),
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
#: ``npm run <脚本>`` / ``pnpm run <脚本>`` 里算验证的脚本名。
|
|
95
|
+
_RUN_SCRIPTS: frozenset[str] = frozenset(
|
|
96
|
+
{"test", "tests", "lint", "build", "check", "typecheck", "verify", "ci"}
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
#: 包一层再执行别的命令的前缀。判断时先剥掉,再看剩下的第一个程序。
|
|
100
|
+
_WRAPPERS: frozenset[str] = frozenset(
|
|
101
|
+
{
|
|
102
|
+
"uv",
|
|
103
|
+
"poetry",
|
|
104
|
+
"pipenv",
|
|
105
|
+
"hatch",
|
|
106
|
+
"pdm",
|
|
107
|
+
"bundle",
|
|
108
|
+
"npx",
|
|
109
|
+
"pnpx",
|
|
110
|
+
"sudo",
|
|
111
|
+
"env",
|
|
112
|
+
"time",
|
|
113
|
+
"exec",
|
|
114
|
+
"command",
|
|
115
|
+
"nohup",
|
|
116
|
+
"nice",
|
|
117
|
+
"stdbuf",
|
|
118
|
+
}
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
#: 解释器名。``python -m pytest`` 走模块规则。
|
|
122
|
+
_PYTHONS: frozenset[str] = frozenset({"python", "python3", "py"})
|
|
123
|
+
|
|
124
|
+
#: shell 名。``bash -c "..."`` 递归看括号里的那条命令。
|
|
125
|
+
_SHELLS: frozenset[str] = frozenset({"bash", "sh", "zsh", "dash"})
|
|
126
|
+
|
|
127
|
+
_SEGMENT_SPLIT = re.compile(r"&&|\|\||[;|\n]")
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def is_verification_command(command: str) -> bool:
|
|
131
|
+
"""这条 shell 命令是不是在跑检查。
|
|
132
|
+
|
|
133
|
+
:param command: ``bash`` 工具收到的原始命令。空串、纯注释、纯赋值都返回 ``False``。
|
|
134
|
+
"""
|
|
135
|
+
return any(_segment_verifies(segment) for segment in _SEGMENT_SPLIT.split(command))
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _segment_verifies(segment: str) -> bool:
|
|
139
|
+
tokens = _tokenize(segment)
|
|
140
|
+
return _tokens_verify(tokens)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _tokenize(text: str) -> list[str]:
|
|
144
|
+
"""按 shell 规则切词。引号不配对时退回空白切分——诊断一条命令不该抛异常。"""
|
|
145
|
+
stripped = text.strip()
|
|
146
|
+
if not stripped or stripped.startswith("#"):
|
|
147
|
+
return []
|
|
148
|
+
try:
|
|
149
|
+
return shlex.split(stripped, comments=True)
|
|
150
|
+
except ValueError:
|
|
151
|
+
return stripped.split()
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _tokens_verify(tokens: list[str]) -> bool:
|
|
155
|
+
significant = _strip_prefix(tokens)
|
|
156
|
+
if not significant:
|
|
157
|
+
return False
|
|
158
|
+
program = _basename(significant[0])
|
|
159
|
+
rest = significant[1:]
|
|
160
|
+
|
|
161
|
+
if program in _SHELLS:
|
|
162
|
+
# ``bash -c "uv run pytest"``:只递归那一个字符串参数,不做完整的 shell 解析。
|
|
163
|
+
return any(" " in argument and _segment_verifies(argument) for argument in rest)
|
|
164
|
+
if program in _WRAPPERS:
|
|
165
|
+
# ``uv run --env-file .env pytest``:在剩余参数里找第一个**已知程序**,
|
|
166
|
+
# 而不是猜哪个参数是选项值。
|
|
167
|
+
index = _first_known_program(rest)
|
|
168
|
+
return index is not None and _tokens_verify(rest[index:])
|
|
169
|
+
if program in _VERIFICATION_TOOLS:
|
|
170
|
+
return True
|
|
171
|
+
if program in _PYTHONS:
|
|
172
|
+
return _python_invokes_verification(rest)
|
|
173
|
+
if program in _MANAGER_COMMANDS:
|
|
174
|
+
return _manager_invokes_verification(program, rest)
|
|
175
|
+
return False
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def _strip_prefix(tokens: list[str]) -> list[str]:
|
|
179
|
+
"""去掉 ``KEY=VALUE`` 环境赋值与 ``timeout 30`` 这类前置修饰。"""
|
|
180
|
+
index = 0
|
|
181
|
+
while index < len(tokens):
|
|
182
|
+
token = tokens[index]
|
|
183
|
+
if "=" in token and not token.startswith("-") and "/" not in token.split("=", 1)[0]:
|
|
184
|
+
index += 1
|
|
185
|
+
continue
|
|
186
|
+
if token == "timeout" and index + 1 < len(tokens):
|
|
187
|
+
index += 2
|
|
188
|
+
continue
|
|
189
|
+
break
|
|
190
|
+
return tokens[index:]
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _first_known_program(tokens: list[str]) -> int | None:
|
|
194
|
+
"""剩余参数里第一个"看起来是程序"的位置。用于穿透 ``uv run`` 这类包装。"""
|
|
195
|
+
for index, token in enumerate(tokens):
|
|
196
|
+
if token.startswith("-"):
|
|
197
|
+
continue
|
|
198
|
+
name = _basename(token)
|
|
199
|
+
if (
|
|
200
|
+
name in _VERIFICATION_TOOLS
|
|
201
|
+
or name in _PYTHONS
|
|
202
|
+
or name in _MANAGER_COMMANDS
|
|
203
|
+
or name in _WRAPPERS
|
|
204
|
+
or name in _SHELLS
|
|
205
|
+
):
|
|
206
|
+
return index
|
|
207
|
+
return None
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _python_invokes_verification(rest: list[str]) -> bool:
|
|
211
|
+
for index, token in enumerate(rest):
|
|
212
|
+
if token == "-m" and index + 1 < len(rest):
|
|
213
|
+
return _basename(rest[index + 1]) in _VERIFICATION_MODULES
|
|
214
|
+
# ``python -m`` 之外的写法(``python manage.py test``)不在保守匹配范围内。
|
|
215
|
+
return False
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def _manager_invokes_verification(program: str, rest: list[str]) -> bool:
|
|
219
|
+
subcommands = _MANAGER_COMMANDS[program]
|
|
220
|
+
arguments = [token for token in rest if not token.startswith("-")]
|
|
221
|
+
if not arguments:
|
|
222
|
+
return False
|
|
223
|
+
first = arguments[0]
|
|
224
|
+
if first in subcommands:
|
|
225
|
+
return True
|
|
226
|
+
if first == "run" and len(arguments) > 1:
|
|
227
|
+
return arguments[1] in _RUN_SCRIPTS
|
|
228
|
+
return False
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def _basename(token: str) -> str:
|
|
232
|
+
"""``/usr/bin/pytest`` → ``pytest``;``pytest.exe`` → ``pytest``。"""
|
|
233
|
+
name = token.replace("\\", "/").rsplit("/", 1)[-1]
|
|
234
|
+
return name[:-4] if name.endswith(".exe") else name
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
# ------------------------------------------------------------------ 本轮证据
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
@dataclass(slots=True)
|
|
241
|
+
class RunEvidence:
|
|
242
|
+
"""一次逻辑 run 的改动与验证记录。
|
|
243
|
+
|
|
244
|
+
"逻辑 run"指 ``AgentSession.prompt()`` 到 ``agent_settled`` 之间的全过程,包含
|
|
245
|
+
自动重试、续跑与压缩恢复:那些都是同一件事的组成部分,不该各自重新记一遍。
|
|
246
|
+
|
|
247
|
+
``pending`` 按 ``tool_call_id`` 暂存调用参数。``tool_execution_end`` 只带结果与
|
|
248
|
+
成败,不看参数就没法知道这次 ``write`` 写的是哪个文件。
|
|
249
|
+
"""
|
|
250
|
+
|
|
251
|
+
modified_paths: list[str] = field(default_factory=list[str])
|
|
252
|
+
verification_commands: list[str] = field(default_factory=list[str])
|
|
253
|
+
reminder_sent: bool = False
|
|
254
|
+
pending: dict[str, tuple[str, dict[str, JsonValue]]] = field(
|
|
255
|
+
default_factory=dict[str, tuple[str, dict[str, JsonValue]]]
|
|
256
|
+
)
|
|
257
|
+
|
|
258
|
+
def reset(self) -> None:
|
|
259
|
+
self.modified_paths.clear()
|
|
260
|
+
self.verification_commands.clear()
|
|
261
|
+
self.pending.clear()
|
|
262
|
+
self.reminder_sent = False
|
|
263
|
+
|
|
264
|
+
def note_start(self, tool_call_id: str, tool_name: str, args: dict[str, JsonValue]) -> None:
|
|
265
|
+
self.pending[tool_call_id] = (tool_name, args)
|
|
266
|
+
|
|
267
|
+
def note_end(self, tool_call_id: str, tool_name: str, *, is_error: bool) -> None:
|
|
268
|
+
"""一次调用结束。失败的不算改动、也不算验证——它什么都没做成。"""
|
|
269
|
+
recorded = self.pending.pop(tool_call_id, None)
|
|
270
|
+
args = recorded[1] if recorded is not None and recorded[0] == tool_name else {}
|
|
271
|
+
if tool_name == "verify":
|
|
272
|
+
# 验证工具本身就是一次检查:它报告失败也说明"检查跑过了、结论是红的"。
|
|
273
|
+
# 与 bash 的规则不同——一条失败的 bash 命令可能只是普通命令出错,
|
|
274
|
+
# 而 verify 的输出永远是检查结果。
|
|
275
|
+
self.verification_commands.append("verify")
|
|
276
|
+
return
|
|
277
|
+
if is_error:
|
|
278
|
+
return
|
|
279
|
+
if tool_name in ("write", "edit"):
|
|
280
|
+
path = args.get("path")
|
|
281
|
+
if isinstance(path, str) and path and path not in self.modified_paths:
|
|
282
|
+
self.modified_paths.append(path)
|
|
283
|
+
return
|
|
284
|
+
if tool_name == "bash":
|
|
285
|
+
command = args.get("command")
|
|
286
|
+
if isinstance(command, str) and is_verification_command(command):
|
|
287
|
+
self.verification_commands.append(command.strip())
|
|
288
|
+
|
|
289
|
+
@property
|
|
290
|
+
def needs_verification(self) -> bool:
|
|
291
|
+
"""改了文件却没有跑过任何验证。"""
|
|
292
|
+
return bool(self.modified_paths) and not self.verification_commands
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
__all__ = ["RunEvidence", "is_verification_command"]
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
"""会话文件的跨进程独占锁。
|
|
2
|
+
|
|
3
|
+
两个进程同时打开同一个会话文件时,会各自把文件读进内存、各自维护"当前叶子"、
|
|
4
|
+
各自追加,父链就交错成两棵树,恢复出来的上下文顺序不可预测。因此给会话文件加一把
|
|
5
|
+
**非阻塞独占锁**,第二个持有者在打开阶段就失败,而不是等到写坏文件之后。
|
|
6
|
+
|
|
7
|
+
## 锁的形状
|
|
8
|
+
|
|
9
|
+
- 锁文件与目标文件同目录,名字是 ``<会话文件>.lock``;
|
|
10
|
+
- POSIX 用 ``fcntl.flock(LOCK_EX | LOCK_NB)``,Windows 用 ``msvcrt.locking(LK_NBLCK)``;
|
|
11
|
+
- 拿不到就抛 :class:`SessionLockedError`,消息里带占用者的 pid;
|
|
12
|
+
- 锁的生命周期是 :class:`~braid_coding_agent.session.manager.SessionManager` 的生命周期,
|
|
13
|
+
``release_lock()`` 或进程退出时释放。
|
|
14
|
+
|
|
15
|
+
## 为什么锁文件不删
|
|
16
|
+
|
|
17
|
+
``flock`` 锁在**打开文件描述**上,不在路径上。删掉锁文件会让后来者创建一个新的
|
|
18
|
+
inode 并锁住它,而第一个进程仍然锁着旧 inode——两边都以为自己独占,这正是锁要
|
|
19
|
+
防的事。所以 ``release()`` 只解锁并关闭描述符,锁文件留在磁盘上;它只有几十字节,
|
|
20
|
+
内容只是给排错用的 pid,不承载任何状态。
|
|
21
|
+
|
|
22
|
+
不用「``O_EXCL`` 创建 + 进程退出时删除」那一套的理由是崩溃残留:进程被
|
|
23
|
+
``SIGKILL`` 之后没人删文件,下一个进程会因为一个死进程的残留文件永久打不开会话。
|
|
24
|
+
``flock`` 由内核在描述符关闭时释放,崩溃不留后遗症。
|
|
25
|
+
|
|
26
|
+
## 描述符为什么包一层 ``FileIO``
|
|
27
|
+
|
|
28
|
+
裸 ``os.open`` 返回的整数描述符在对象被回收时不会关闭,锁会一直挂到进程结束;
|
|
29
|
+
包成 :class:`io.FileIO` 之后,"管理器对象没了"就等于"描述符关了"等于"锁放了"。
|
|
30
|
+
显式 ``release_lock()`` 仍是确定性路径,垃圾回收只是不给悬着的锁留活口。
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
from __future__ import annotations
|
|
34
|
+
|
|
35
|
+
import errno
|
|
36
|
+
import json
|
|
37
|
+
import os
|
|
38
|
+
import sys
|
|
39
|
+
import time
|
|
40
|
+
from io import FileIO
|
|
41
|
+
from typing import Final
|
|
42
|
+
|
|
43
|
+
from braid_ai.types import JsonValue
|
|
44
|
+
|
|
45
|
+
if sys.platform == "win32": # pragma: no cover - 开发与 CI 都在 POSIX 上
|
|
46
|
+
import msvcrt
|
|
47
|
+
else:
|
|
48
|
+
import fcntl
|
|
49
|
+
|
|
50
|
+
__all__ = ["LOCK_SUFFIX", "SessionFileLock", "SessionLockedError"]
|
|
51
|
+
|
|
52
|
+
#: 锁文件的扩展名。与目标文件同目录,便于人工定位。
|
|
53
|
+
LOCK_SUFFIX: Final[str] = ".lock"
|
|
54
|
+
|
|
55
|
+
#: 锁文件里记录占用者信息的长度上限。超出的内容一律忽略。
|
|
56
|
+
_HOLDER_READ_LIMIT: Final[int] = 512
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class SessionLockedError(RuntimeError):
|
|
60
|
+
"""会话文件已被另一个写入者占用。
|
|
61
|
+
|
|
62
|
+
:param path: 会话文件路径。
|
|
63
|
+
:param lock_path: 锁文件路径。
|
|
64
|
+
:param holder_pid: 锁文件里记录的占用者 pid;读不出来时为 ``None``。
|
|
65
|
+
"""
|
|
66
|
+
|
|
67
|
+
def __init__(self, path: str, lock_path: str, holder_pid: int | None) -> None:
|
|
68
|
+
self.path = path
|
|
69
|
+
self.lock_path = lock_path
|
|
70
|
+
self.holder_pid = holder_pid
|
|
71
|
+
who = f"进程 {holder_pid}" if holder_pid is not None else "另一个进程"
|
|
72
|
+
super().__init__(
|
|
73
|
+
f"会话文件已被{who}占用:{path}\n"
|
|
74
|
+
f"锁文件:{lock_path}\n"
|
|
75
|
+
"同一个会话文件同一时刻只能有一个写入者。请先结束占用它的进程,"
|
|
76
|
+
"或者用 --session 指定别的会话文件。"
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _try_lock(descriptor: int) -> bool:
|
|
81
|
+
"""尝试取独占锁。已被占用返回 ``False``,其余错误照常抛出。"""
|
|
82
|
+
if sys.platform == "win32": # pragma: no cover
|
|
83
|
+
os.lseek(descriptor, 0, os.SEEK_SET)
|
|
84
|
+
try:
|
|
85
|
+
msvcrt.locking(descriptor, msvcrt.LK_NBLCK, 1)
|
|
86
|
+
except OSError as exc:
|
|
87
|
+
if exc.errno in (errno.EACCES, errno.EDEADLK):
|
|
88
|
+
return False
|
|
89
|
+
raise
|
|
90
|
+
return True
|
|
91
|
+
try:
|
|
92
|
+
fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
93
|
+
except BlockingIOError:
|
|
94
|
+
return False
|
|
95
|
+
return True
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _unlock(descriptor: int) -> None:
|
|
99
|
+
"""释放独占锁。未持有时是空操作。"""
|
|
100
|
+
if sys.platform == "win32": # pragma: no cover
|
|
101
|
+
os.lseek(descriptor, 0, os.SEEK_SET)
|
|
102
|
+
msvcrt.locking(descriptor, msvcrt.LK_UNLCK, 1)
|
|
103
|
+
return
|
|
104
|
+
fcntl.flock(descriptor, fcntl.LOCK_UN)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _read_holder(handle: FileIO) -> int | None:
|
|
108
|
+
"""从锁文件里读占用者 pid。文件坏了或没有记录时返回 ``None``。"""
|
|
109
|
+
handle.seek(0)
|
|
110
|
+
raw = handle.read(_HOLDER_READ_LIMIT)
|
|
111
|
+
if not raw:
|
|
112
|
+
return None
|
|
113
|
+
try:
|
|
114
|
+
parsed: JsonValue = json.loads(raw)
|
|
115
|
+
except (json.JSONDecodeError, UnicodeDecodeError):
|
|
116
|
+
return None
|
|
117
|
+
if not isinstance(parsed, dict):
|
|
118
|
+
return None
|
|
119
|
+
pid = parsed.get("pid")
|
|
120
|
+
return pid if isinstance(pid, int) and not isinstance(pid, bool) else None
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _write_holder(handle: FileIO) -> None:
|
|
124
|
+
"""把本进程的 pid 写进锁文件,让下一个撞锁的进程能说出"是谁占着"。"""
|
|
125
|
+
stamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
|
|
126
|
+
payload = json.dumps({"pid": os.getpid(), "acquiredAt": stamp}, ensure_ascii=False)
|
|
127
|
+
handle.seek(0)
|
|
128
|
+
handle.truncate(0)
|
|
129
|
+
handle.write(payload.encode("utf-8"))
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
class SessionFileLock:
|
|
133
|
+
"""``<会话文件>.lock`` 上的一把非阻塞独占锁。"""
|
|
134
|
+
|
|
135
|
+
def __init__(self, session_file: str) -> None:
|
|
136
|
+
self._session_file = os.path.abspath(session_file)
|
|
137
|
+
self._lock_path = self._session_file + LOCK_SUFFIX
|
|
138
|
+
self._handle: FileIO | None = None
|
|
139
|
+
|
|
140
|
+
@property
|
|
141
|
+
def session_file(self) -> str:
|
|
142
|
+
return self._session_file
|
|
143
|
+
|
|
144
|
+
@property
|
|
145
|
+
def lock_path(self) -> str:
|
|
146
|
+
"""锁文件路径。测试与排错用。"""
|
|
147
|
+
return self._lock_path
|
|
148
|
+
|
|
149
|
+
@property
|
|
150
|
+
def held(self) -> bool:
|
|
151
|
+
return self._handle is not None
|
|
152
|
+
|
|
153
|
+
def acquire(self) -> None:
|
|
154
|
+
"""取锁。已被占用时抛 :class:`SessionLockedError`(不等待、不重试)。
|
|
155
|
+
|
|
156
|
+
:raises SessionLockedError: 另一个进程或本进程的另一个管理器正持有锁。
|
|
157
|
+
"""
|
|
158
|
+
if self._handle is not None:
|
|
159
|
+
return
|
|
160
|
+
descriptor = os.open(self._lock_path, os.O_RDWR | os.O_CREAT, 0o600)
|
|
161
|
+
handle = FileIO(descriptor, "r+", closefd=True)
|
|
162
|
+
if not _try_lock(handle.fileno()):
|
|
163
|
+
holder = _read_holder(handle)
|
|
164
|
+
handle.close()
|
|
165
|
+
raise SessionLockedError(self._session_file, self._lock_path, holder)
|
|
166
|
+
self._handle = handle
|
|
167
|
+
_write_holder(handle)
|
|
168
|
+
|
|
169
|
+
def release(self) -> None:
|
|
170
|
+
"""释放锁(幂等)。锁文件留在磁盘上,理由见模块文档。"""
|
|
171
|
+
handle = self._handle
|
|
172
|
+
if handle is None:
|
|
173
|
+
return
|
|
174
|
+
self._handle = None
|
|
175
|
+
_unlock(handle.fileno())
|
|
176
|
+
handle.close()
|