coding-agent-toolchain 1.0.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.
@@ -0,0 +1,8 @@
1
+ """Standalone toolchain compatibility, skill synchronization, and temp-dir governance CLIs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ TOOL_NAME = "agent-toolchain"
6
+ __version__ = "1.0.0"
7
+
8
+ __all__ = ["TOOL_NAME", "__version__"]
@@ -0,0 +1,108 @@
1
+ """Structured error codes and exception taxonomy across Agent Toolchain CLIs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+
7
+ VALID_ERROR_CODE = re.compile(r"^[A-Z][A-Z0-9_]{2,63}$")
8
+
9
+
10
+ class ErrorCode:
11
+ """Stable machine-readable error codes emitted on refusal or failure."""
12
+
13
+ CLI_INVALID_ARGS = "CLI_INVALID_ARGS"
14
+ EXECUTION_LOCK_UNAVAILABLE = "EXECUTION_LOCK_UNAVAILABLE"
15
+ EXECUTION_LOCK_TIMEOUT = "EXECUTION_LOCK_TIMEOUT"
16
+ RUNTIME_INTEGRITY_ERROR = "RUNTIME_INTEGRITY_ERROR"
17
+ REPO_INVALID = "REPO_INVALID"
18
+ BRANCH_PROTECTED = "BRANCH_PROTECTED"
19
+ DETACHED_HEAD = "DETACHED_HEAD"
20
+ UNBORN_REPO = "UNBORN_REPO"
21
+ UPSTREAM_CONFLICT = "UPSTREAM_CONFLICT"
22
+ REMOTE_UNAVAILABLE = "REMOTE_UNAVAILABLE"
23
+ REMOTE_DIVERGED = "REMOTE_DIVERGED"
24
+ REMOTE_BEHIND = "REMOTE_BEHIND"
25
+ REMOTE_MISSING = "REMOTE_MISSING"
26
+ SCOPE_INVALID = "SCOPE_INVALID"
27
+ INDEX_UNCLEAN = "INDEX_UNCLEAN"
28
+ WORKING_TREE_DIRTY = "WORKING_TREE_DIRTY"
29
+ WHITESPACE_VIOLATION = "WHITESPACE_VIOLATION"
30
+ BINARY_SIZE_EXCEEDED = "BINARY_SIZE_EXCEEDED"
31
+ CONTENT_SCAN_BLOCKED = "CONTENT_SCAN_BLOCKED"
32
+ EXTERNAL_SCANNER_FAILED = "EXTERNAL_SCANNER_FAILED"
33
+ EXTERNAL_SCANNER_BLOCKED = "EXTERNAL_SCANNER_BLOCKED"
34
+ SOURCE_REVIEW_BLOCKED = "SOURCE_REVIEW_BLOCKED"
35
+ FIXTURE_EXCEPTION_BLOCKED = "FIXTURE_EXCEPTION_BLOCKED"
36
+ SNAPSHOT_EVIDENCE_REJECTED = "SNAPSHOT_EVIDENCE_REJECTED"
37
+ POLICY_DENIED = "POLICY_DENIED"
38
+ HOOK_FAILED = "HOOK_FAILED"
39
+ COMMIT_FAILED = "COMMIT_FAILED"
40
+ PUSH_FAILED = "PUSH_FAILED"
41
+ POST_VERIFY_FAILED = "POST_VERIFY_FAILED"
42
+ RETIREMENT_BLOCKED = "RETIREMENT_BLOCKED"
43
+ CONTROLLER_UNAVAILABLE = "CONTROLLER_UNAVAILABLE"
44
+ BOOTSTRAP_BLOCKED = "BOOTSTRAP_BLOCKED"
45
+ BOOTSTRAP_FAILED = "BOOTSTRAP_FAILED"
46
+ INTEGRATION_PUBLISH_BLOCKED = "INTEGRATION_PUBLISH_BLOCKED"
47
+ INTEGRATION_PUBLISH_FAILED = "INTEGRATION_PUBLISH_FAILED"
48
+ SYNC_FAILED = "SYNC_FAILED"
49
+ TEMP_DIR_FAILED = "TEMP_DIR_FAILED"
50
+ SUMMARY_SERIALIZATION_ERROR = "SUMMARY_SERIALIZATION_ERROR"
51
+ INTERNAL_ERROR = "INTERNAL_ERROR"
52
+
53
+
54
+ class ToolchainError(RuntimeError):
55
+ """Fail-closed operational blocker or terminal failure with a structured code."""
56
+
57
+ def __init__(
58
+ self,
59
+ code: str,
60
+ message: str,
61
+ *,
62
+ status: str = "blocked",
63
+ final_phase: str = "preflight",
64
+ next_action: str | None = None,
65
+ exit_code: int = 1,
66
+ commit_created: bool = False,
67
+ commit_sha: str | None = None,
68
+ push_executed: bool = False,
69
+ push_result: str = "not_run",
70
+ mode_result: dict[str, object] | None = None,
71
+ resume: dict[str, object] | None = None,
72
+ diagnostics: dict[str, object] | None = None,
73
+ scan_diagnostic: dict[str, object] | None = None,
74
+ reviewed_sensitive_sources: list[dict[str, object]] | None = None,
75
+ warnings: list[str] | None = None,
76
+ ) -> None:
77
+ if VALID_ERROR_CODE.fullmatch(code) is None:
78
+ raise ValueError(f"invalid structured error_code: {code!r}")
79
+ if status not in {"blocked", "failed"}:
80
+ raise ValueError(f"invalid error status: {status!r}")
81
+ self.code = code
82
+ self.message = message
83
+ self.status = status
84
+ self.final_phase = final_phase
85
+ self.next_action = (
86
+ next_action
87
+ if next_action is not None
88
+ else ("inspect_failure" if status == "failed" else "resolve_blocker_and_retry")
89
+ )
90
+ self.exit_code = exit_code
91
+ self.commit_created = commit_created
92
+ self.commit_sha = commit_sha
93
+ self.push_executed = push_executed
94
+ self.push_result = push_result
95
+ self.mode_result = dict(mode_result) if mode_result is not None else {}
96
+ self.resume = dict(resume) if resume is not None else None
97
+ self.diagnostics = dict(diagnostics) if diagnostics is not None else None
98
+ self.scan_diagnostic = dict(scan_diagnostic) if scan_diagnostic is not None else None
99
+ self.reviewed_sensitive_sources = (
100
+ [dict(item) for item in reviewed_sensitive_sources]
101
+ if reviewed_sensitive_sources is not None
102
+ else None
103
+ )
104
+ self.warnings = list(warnings or [])
105
+ super().__init__(message)
106
+
107
+
108
+ FinalizerError = ToolchainError
@@ -0,0 +1,284 @@
1
+ """Portable Git invocation, validation, binary detection, and isolated index helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterator
6
+ from contextlib import contextmanager
7
+ import os
8
+ from pathlib import Path
9
+ import re
10
+ import shutil
11
+ import subprocess
12
+ import tempfile
13
+ from typing import Any
14
+
15
+ from agent_toolchain.errors import ErrorCode, ToolchainError
16
+
17
+ FULL_OID_RE = re.compile(r"^(?:[0-9a-f]{40}|[0-9a-f]{64})$")
18
+ SAFE_REMOTE_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._/@:-]{0,127}$")
19
+ DEFAULT_LOCAL_GIT_TIMEOUT = 120.0
20
+ DEFAULT_REMOTE_GIT_TIMEOUT = 120.0
21
+ BINARY_CHUNK_SIZE = 1024 * 1024
22
+
23
+
24
+ def remote_git_timeout() -> float:
25
+ """Resolve remote git timeout, allowing bounded positive AT_REMOTE_GIT_TIMEOUT/GF_REMOTE_GIT_TIMEOUT override."""
26
+ raw = (
27
+ os.environ.get("AT_REMOTE_GIT_TIMEOUT", "").strip()
28
+ or os.environ.get("GF_REMOTE_GIT_TIMEOUT", "").strip()
29
+ )
30
+ if raw:
31
+ try:
32
+ val = float(raw)
33
+ except ValueError:
34
+ return DEFAULT_REMOTE_GIT_TIMEOUT
35
+ if 0.0 < val <= 300.0:
36
+ return val
37
+ return DEFAULT_REMOTE_GIT_TIMEOUT
38
+
39
+
40
+ def find_git(path_env: str | None = None) -> str:
41
+ """Resolve the git executable portably via PATH."""
42
+ resolved = shutil.which("git", path=path_env) if path_env is not None else shutil.which("git")
43
+ if not resolved:
44
+ raise ToolchainError(
45
+ ErrorCode.REPO_INVALID,
46
+ "PATH 中未找到可用的 git 可执行文件",
47
+ final_phase="cli",
48
+ )
49
+ return resolved
50
+
51
+
52
+ def clean_git_env(extra: dict[str, str] | None = None) -> dict[str, str]:
53
+ """Return a clean deterministic Git environment preserving caller PATH/HOME/TMPDIR."""
54
+ env = dict(os.environ)
55
+ env["LC_ALL"] = "C"
56
+ env["GIT_TERMINAL_PROMPT"] = "0"
57
+ env["GIT_OPTIONAL_LOCKS"] = "0"
58
+ if extra:
59
+ env.update(extra)
60
+ return env
61
+
62
+
63
+ def validate_oid(value: str, label: str = "OID") -> str:
64
+ if FULL_OID_RE.fullmatch(value) is None:
65
+ raise ToolchainError(
66
+ ErrorCode.CLI_INVALID_ARGS,
67
+ f"{label} 必须是完整小写十六进制 OID (40 或 64 位)",
68
+ final_phase="cli",
69
+ )
70
+ return value
71
+
72
+
73
+ def validate_remote_name(remote: str) -> str:
74
+ if (
75
+ not remote
76
+ or remote.startswith("-")
77
+ or any(ch.isspace() or ord(ch) < 0x20 or ord(ch) == 0x7F for ch in remote)
78
+ or ".." in remote
79
+ or "\\" in remote
80
+ or "\0" in remote
81
+ or SAFE_REMOTE_RE.fullmatch(remote) is None
82
+ ):
83
+ raise ToolchainError(
84
+ ErrorCode.CLI_INVALID_ARGS,
85
+ f"非法的 remote 名称: {remote!r}",
86
+ final_phase="cli",
87
+ )
88
+ return remote
89
+
90
+
91
+ def validate_branch_name(branch: str) -> str:
92
+ if (
93
+ not branch
94
+ or branch.startswith("-")
95
+ or branch.startswith("/")
96
+ or branch.endswith("/")
97
+ or branch.endswith(".")
98
+ or branch.endswith(".lock")
99
+ or branch.startswith("refs/")
100
+ or ".." in branch
101
+ or "@{" in branch
102
+ or "//" in branch
103
+ or any(ch in branch for ch in (" ", "\t", "\n", "\r", "\0", "~", "^", ":", "?", "*", "[", "\\"))
104
+ ):
105
+ raise ToolchainError(
106
+ ErrorCode.CLI_INVALID_ARGS,
107
+ f"非法的 branch 名称: {branch!r}",
108
+ final_phase="cli",
109
+ )
110
+ return branch
111
+
112
+
113
+ def run_git(
114
+ repo: Path | None,
115
+ *arguments: str,
116
+ timeout: float = DEFAULT_LOCAL_GIT_TIMEOUT,
117
+ check: bool = False,
118
+ text: bool = False,
119
+ env: dict[str, str] | None = None,
120
+ input_data: bytes | str | None = None,
121
+ ) -> subprocess.CompletedProcess[Any]:
122
+ """Run git safely with clean env, close_fds=True, and explicit timeouts."""
123
+ resolved_git = find_git(env.get("PATH") if env else None)
124
+ command = [resolved_git]
125
+ if repo is not None:
126
+ command.extend(["-C", str(repo)])
127
+ command.extend(arguments)
128
+ run_env = clean_git_env(env) if env is None else {
129
+ **env,
130
+ "LC_ALL": "C",
131
+ "GIT_TERMINAL_PROMPT": "0",
132
+ "GIT_OPTIONAL_LOCKS": "0",
133
+ }
134
+ try:
135
+ completed = subprocess.run(
136
+ command,
137
+ input=input_data,
138
+ capture_output=True,
139
+ text=text,
140
+ timeout=timeout,
141
+ env=run_env,
142
+ close_fds=True,
143
+ check=False,
144
+ )
145
+ except subprocess.TimeoutExpired as exc:
146
+ raise ToolchainError(
147
+ ErrorCode.REMOTE_UNAVAILABLE if "ls-remote" in arguments or "fetch" in arguments or "push" in arguments else ErrorCode.INTERNAL_ERROR,
148
+ f"git 命令执行超时 ({arguments[0] if arguments else 'git'})",
149
+ status="failed",
150
+ ) from exc
151
+ except OSError as exc:
152
+ raise ToolchainError(
153
+ ErrorCode.INTERNAL_ERROR,
154
+ f"无法执行 git 命令: {exc}",
155
+ status="failed",
156
+ ) from exc
157
+ if check and completed.returncode != 0:
158
+ raise subprocess.CalledProcessError(
159
+ completed.returncode, command, output=completed.stdout, stderr=completed.stderr
160
+ )
161
+ return completed
162
+
163
+
164
+ def parse_nul_records(raw: bytes) -> list[str]:
165
+ """Decode strict UTF-8 NUL-delimited Git records, preserving empty middle elements."""
166
+ if not raw:
167
+ return []
168
+ if not raw.endswith(b"\0"):
169
+ raise ValueError("unterminated NUL record stream")
170
+ parts = raw.split(b"\0")
171
+ parts.pop()
172
+ return [part.decode("utf-8", errors="strict") for part in parts]
173
+
174
+
175
+ def is_binary_bytes(data: bytes) -> bool:
176
+ """Single canonical binary check across worktree, candidate, index, and history."""
177
+ return b"\x00" in data
178
+
179
+
180
+ def inspect_file_stream(path: Path, max_bytes: int | None = None) -> tuple[bool, int]:
181
+ """Stream-inspect a regular file for NUL bytes and byte size."""
182
+ binary = False
183
+ total = 0
184
+ with path.open("rb") as stream:
185
+ while True:
186
+ chunk = stream.read(BINARY_CHUNK_SIZE)
187
+ if not chunk:
188
+ break
189
+ total += len(chunk)
190
+ if max_bytes is not None and total > max_bytes:
191
+ raise ValueError(f"file exceeds scan byte budget ({max_bytes} bytes)")
192
+ if not binary and b"\x00" in chunk:
193
+ binary = True
194
+ return binary, total
195
+
196
+
197
+ def read_blob_size(repo: Path, oid: str, *, env: dict[str, str] | None = None) -> int:
198
+ """Check object existence/size cleanly via git cat-file -s before reading blob bytes."""
199
+ completed = run_git(repo, "cat-file", "-s", oid, env=env)
200
+ if completed.returncode != 0:
201
+ raise ToolchainError(
202
+ ErrorCode.INTERNAL_ERROR,
203
+ f"无法读取 Git 对象大小: {oid}",
204
+ status="failed",
205
+ )
206
+ return int(completed.stdout.decode("ascii").strip())
207
+
208
+
209
+ def read_blob_bytes(
210
+ repo: Path,
211
+ oid: str,
212
+ *,
213
+ max_bytes: int,
214
+ env: dict[str, str] | None = None,
215
+ ) -> bytes:
216
+ """Verify blob byte size BEFORE materializing the blob in memory."""
217
+ size = read_blob_size(repo, oid, env=env)
218
+ if size > max_bytes:
219
+ raise ValueError(f"Git blob {oid} exceeds scan byte budget ({size} > {max_bytes})")
220
+ completed = run_git(repo, "cat-file", "blob", oid, env=env)
221
+ if completed.returncode != 0:
222
+ raise ToolchainError(
223
+ ErrorCode.INTERNAL_ERROR,
224
+ f"无法读取 Git blob 内容: {oid}",
225
+ status="failed",
226
+ )
227
+ return completed.stdout
228
+
229
+
230
+ def read_baseline_blob(
231
+ repo: Path,
232
+ ref_expr: str,
233
+ path: str,
234
+ *,
235
+ max_bytes: int,
236
+ env: dict[str, str] | None = None,
237
+ ) -> tuple[str | None, bytes | None]:
238
+ """Read `path` blob oid and bytes from `ref_expr` if present as a regular blob."""
239
+ clean_env = clean_git_env(env)
240
+ ls = run_git(repo, "--literal-pathspecs", "ls-tree", "-z", ref_expr, "--", path, env=clean_env)
241
+ if ls.returncode != 0 or not ls.stdout:
242
+ return None, None
243
+ entries = parse_nul_records(ls.stdout)
244
+ if len(entries) != 1:
245
+ return None, None
246
+ meta, _, _ = entries[0].partition("\t")
247
+ parts = meta.split()
248
+ if len(parts) != 3 or parts[1] != "blob":
249
+ return None, None
250
+ oid = parts[2]
251
+ return oid, read_blob_bytes(repo, oid, max_bytes=max_bytes, env=clean_env)
252
+
253
+
254
+ @contextmanager
255
+ def isolated_staging_env(
256
+ repo: Path,
257
+ git_dir: Path,
258
+ common_dir: Path,
259
+ *,
260
+ base_env: dict[str, str] | None = None,
261
+ ) -> Iterator[tuple[dict[str, str], Path]]:
262
+ """Build an isolated temporary GIT_INDEX_FILE + temp object store without touching .git/index or .git/objects."""
263
+ with tempfile.TemporaryDirectory(prefix="at-isolated-stage-") as temporary:
264
+ tmp_path = Path(temporary)
265
+ temp_index = tmp_path / "index"
266
+ real_index = git_dir / "index"
267
+ if real_index.exists():
268
+ if real_index.is_symlink() or not real_index.is_file():
269
+ raise ToolchainError(
270
+ ErrorCode.REPO_INVALID,
271
+ "拒绝非普通文件类型的 Git index",
272
+ final_phase="preflight",
273
+ )
274
+ shutil.copy2(real_index, temp_index)
275
+ temp_objects = tmp_path / "objects"
276
+ temp_objects.mkdir(mode=0o700)
277
+ alt_objects = common_dir / "objects"
278
+ existing_alt = (base_env or os.environ).get("GIT_ALTERNATE_OBJECT_DIRECTORIES", "")
279
+ alts = os.pathsep.join(part for part in (str(alt_objects), existing_alt) if part)
280
+ env = clean_git_env(base_env)
281
+ env["GIT_INDEX_FILE"] = str(temp_index)
282
+ env["GIT_OBJECT_DIRECTORY"] = str(temp_objects)
283
+ env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = alts
284
+ yield env, temp_index
@@ -0,0 +1,55 @@
1
+ """Strict JSON parsing, canonical serialization, and hashing helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+
11
+ class DuplicateKeyError(ValueError):
12
+ """Raised when a JSON object declares a duplicate key."""
13
+
14
+
15
+ class NonFiniteConstantError(ValueError):
16
+ """Raised when JSON contains NaN, Infinity, or -Infinity."""
17
+
18
+
19
+ def unique_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
20
+ """Build a dict while rejecting duplicate JSON object keys."""
21
+ result: dict[str, Any] = {}
22
+ for key, value in pairs:
23
+ if key in result:
24
+ raise DuplicateKeyError(f"duplicate JSON key: {key!r}")
25
+ result[key] = value
26
+ return result
27
+
28
+
29
+ def _reject_constant(token: str) -> Any:
30
+ raise NonFiniteConstantError(f"non-finite JSON constant is not allowed: {token}")
31
+
32
+
33
+ def loads_unique(raw: str | bytes, *, allow_nonfinite: bool = False) -> Any:
34
+ """Decode strict UTF-8 JSON rejecting duplicate keys and optional non-finite numbers."""
35
+ text = raw.decode("utf-8", errors="strict") if isinstance(raw, bytes) else raw
36
+ kwargs: dict[str, Any] = {"object_pairs_hook": unique_object}
37
+ if not allow_nonfinite:
38
+ kwargs["parse_constant"] = _reject_constant
39
+ return json.loads(text, **kwargs)
40
+
41
+
42
+ def sha256_bytes(data: bytes) -> str:
43
+ return hashlib.sha256(data).hexdigest()
44
+
45
+
46
+ def sha256_file(path: Path) -> str:
47
+ digest = hashlib.sha256()
48
+ with path.open("rb") as stream:
49
+ for chunk in iter(lambda: stream.read(1024 * 1024), b""):
50
+ digest.update(chunk)
51
+ return digest.hexdigest()
52
+
53
+
54
+ def canonical_json(value: Any) -> bytes:
55
+ return (json.dumps(value, ensure_ascii=False, sort_keys=True, indent=2) + "\n").encode("utf-8")