git-finalizer 2.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,3044 @@
1
+ #!/usr/bin/env python3
2
+ """Validate and atomically stage versioned tool/binary Skill pairs."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import ast
8
+ import base64
9
+ from collections.abc import Sequence
10
+ from contextlib import contextmanager
11
+ import fcntl
12
+ import hashlib
13
+ import io
14
+ import json
15
+ import os
16
+ from pathlib import Path
17
+ import re
18
+ import shutil
19
+ import stat
20
+ import subprocess
21
+ import sys
22
+ import tarfile
23
+ import tempfile
24
+ import time
25
+ import tomllib
26
+ from typing import Any
27
+
28
+ VERSION = "2.0.0"
29
+ SCHEMA_VERSION = 1
30
+ TOOL_SKILL_MANIFEST_SCHEMA_VERSION = 2
31
+ SKILL_NAME = "git-change-delivery"
32
+ COMPATIBILITY_SKILL_NAME = "three-tool-git-workflow"
33
+ COMPATIBILITY_BUNDLE_PATH = (
34
+ Path("compatibility") / COMPATIBILITY_SKILL_NAME / "SKILL.md"
35
+ )
36
+ SKILL_PAYLOAD = (
37
+ "SKILL.md",
38
+ "quick_validate.py",
39
+ "unpublished_queue.py",
40
+ "references/context-loader.md",
41
+ "references/git-finalizer.md",
42
+ "references/snapshot-runner.md",
43
+ "references/unpublished-queue.md",
44
+ )
45
+ HEX_SHA256 = re.compile(r"[0-9a-f]{64}\Z")
46
+ FULL_GIT_OID = re.compile(r"[0-9a-f]{40,64}\Z")
47
+ SAFE_NAME = re.compile(r"[a-z0-9][a-z0-9._-]*\Z")
48
+ VERSION_LITERAL_RE = re.compile(r"[0-9]+\.[0-9]+\.[0-9]+\Z")
49
+ DEFAULT_LOCK_TIMEOUT = 10.0
50
+ # Payload-tree digests of previously released canonical Skill lines that may
51
+ # legally sit in production before an upgrade. Never add a digest produced by
52
+ # local hand-editing. Keep RELEASED_CANONICAL_SKILL_SHA256 strictly bound to
53
+ # digests published in tagged/integrated git history.
54
+ RELEASED_CANONICAL_SKILL_SHA256 = frozenset(
55
+ {
56
+ # Provider-neutral payload of the first shipped canonical line.
57
+ "ff6d5bea2807b2c884c2ec5bee441e5fe8060abd9d03c0520c57ce39fe37adb5",
58
+ # Canonical payload carried by the two tagged releases of that line.
59
+ "3c8679b6cfd6578da41007feeea43e7ff83e8152e3daea9ab9154055642a92e2",
60
+ # Canonical payload carried by the merged live-policy release.
61
+ "7b85ec9da739bd60f76736ae6352e642dbf880bbd089058cce4cf7a9c0b5c665",
62
+ # Canonical payload carried by the handoff-documentation release, which
63
+ # is also the installed production tree this batch upgrades from.
64
+ "9c05e5b279731a37b3ce15e2fbda7ae9962f81355cbafb86fa410f28ec19f527",
65
+ # Canonical payload carried by the integration-boundary release and by
66
+ # the first publicly released line after it; both tags shipped it
67
+ # unchanged, so a production tree holding it is released lineage.
68
+ "0c82bceb12edde749aa6deddab25acb4ec083aeea92a37970ec64179ef92726b",
69
+ # Payload independently attested by the next published tag.
70
+ "943ebf4e56ae344cf88ab3dc579d5e497663b052c8ccbade5c42f1f52b5efa93",
71
+ # Published canonical payload at commit 67e3e6c.
72
+ "288d3126d9459913714aa2e3934773111b2d4430fb73a8385fd33511807a823c",
73
+ # Published canonical payload at v1.9.9 (ceae77f).
74
+ "010cb09faf50921149b5d22b26093d9445d15461e8d3f10b7faff35259cd8e45",
75
+ }
76
+ )
77
+
78
+
79
+ class SyncError(Exception):
80
+ """A validation or safe activation condition was not met."""
81
+
82
+
83
+ def canonical_json(value: Any) -> bytes:
84
+ return (
85
+ json.dumps(value, ensure_ascii=False, sort_keys=True, indent=2) + "\n"
86
+ ).encode()
87
+
88
+
89
+ def sha256_bytes(value: bytes) -> str:
90
+ return hashlib.sha256(value).hexdigest()
91
+
92
+
93
+ def sha256_file(path: Path) -> str:
94
+ digest = hashlib.sha256()
95
+ with path.open("rb") as stream:
96
+ for chunk in iter(lambda: stream.read(1024 * 1024), b""):
97
+ digest.update(chunk)
98
+ return digest.hexdigest()
99
+
100
+
101
+ def read_json(path: Path) -> dict[str, Any]:
102
+ try:
103
+ raw = path.read_bytes()
104
+ value = json.loads(raw.decode("utf-8"))
105
+ except (OSError, UnicodeError, json.JSONDecodeError) as exc:
106
+ raise SyncError(f"invalid JSON {path}: {exc}") from exc
107
+ if not isinstance(value, dict):
108
+ raise SyncError(f"JSON root must be an object: {path}")
109
+ if raw != canonical_json(value):
110
+ raise SyncError(f"JSON is not deterministically serialized: {path}")
111
+ return value
112
+
113
+
114
+ def write_json(path: Path, value: dict[str, Any], mode: int = 0o600) -> None:
115
+ path.write_bytes(canonical_json(value))
116
+ path.chmod(mode)
117
+
118
+
119
+ def require_regular(path: Path, label: str) -> None:
120
+ if path.is_symlink() or not path.is_file():
121
+ raise SyncError(f"{label} is not a regular file: {path}")
122
+
123
+
124
+ def require_owned_directory(path: Path, *, create: bool = False) -> None:
125
+ if create and not path.exists():
126
+ path.mkdir(mode=0o700, parents=True)
127
+ if path.is_symlink() or not path.is_dir():
128
+ raise SyncError(f"directory is missing or unsafe: {path}")
129
+ if path.stat().st_uid != os.getuid():
130
+ raise SyncError(f"directory is not owned by current user: {path}")
131
+
132
+
133
+ def _flock_exclusive_bounded(descriptor: int, *, timeout: float = DEFAULT_LOCK_TIMEOUT, label: str = "lock") -> None:
134
+ deadline = time.monotonic() + timeout
135
+ while True:
136
+ try:
137
+ fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB)
138
+ return
139
+ except BlockingIOError as exc:
140
+ if time.monotonic() >= deadline:
141
+ raise SyncError(f"timed out waiting for {label}") from exc
142
+ time.sleep(0.05)
143
+
144
+
145
+ @contextmanager
146
+ def deployment_lock(*roots: Path, timeout: float = DEFAULT_LOCK_TIMEOUT):
147
+ """Serialize installers through the same persistent locks, including rollback."""
148
+ descriptors = []
149
+ try:
150
+ for root in sorted({path.absolute() for path in roots}):
151
+ require_owned_directory(root, create=True)
152
+ descriptor = os.open(
153
+ root / ".tool-skill-sync.lock",
154
+ os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW | os.O_CLOEXEC,
155
+ 0o600,
156
+ )
157
+ descriptors.append(descriptor)
158
+ info = os.fstat(descriptor)
159
+ if not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid() or info.st_mode & 0o077:
160
+ raise SyncError("unsafe deployment lock")
161
+ _flock_exclusive_bounded(descriptor, timeout=timeout, label="deployment lock")
162
+ yield
163
+ finally:
164
+ for descriptor in reversed(descriptors):
165
+ os.close(descriptor)
166
+
167
+
168
+ def tree_sha256(root: Path, relative_paths: Sequence[str]) -> str:
169
+ lines: list[str] = []
170
+ for relative in relative_paths:
171
+ path = root / relative
172
+ require_regular(path, "Skill payload")
173
+ lines.append(f"{sha256_file(path)} {relative}\n")
174
+ return sha256_bytes("".join(lines).encode())
175
+
176
+
177
+ def aggregate_hash(values: dict[str, str]) -> str:
178
+ return sha256_bytes(canonical_json(values))
179
+
180
+
181
+ def run(
182
+ arguments: Sequence[str],
183
+ *,
184
+ cwd: Path | None = None,
185
+ env: dict[str, str] | None = None,
186
+ ) -> subprocess.CompletedProcess[str]:
187
+ return subprocess.run(
188
+ arguments,
189
+ cwd=cwd,
190
+ env=env,
191
+ check=False,
192
+ capture_output=True,
193
+ text=True,
194
+ timeout=30,
195
+ )
196
+
197
+
198
+ def git(repo: Path, *arguments: str) -> str:
199
+ result = run(("git", "-C", str(repo), *arguments))
200
+ if result.returncode != 0:
201
+ detail = result.stderr.strip() or result.stdout.strip() or "unknown git error"
202
+ raise SyncError(f"git {' '.join(arguments)} failed for {repo}: {detail}")
203
+ return result.stdout.strip()
204
+
205
+
206
+ def git_head(repo: Path) -> str:
207
+ head = git(repo, "rev-parse", "HEAD")
208
+ if not FULL_GIT_OID.fullmatch(head):
209
+ raise SyncError(f"repository HEAD is not a full object id: {repo}")
210
+ return head
211
+
212
+
213
+ def git_dirty(repo: Path) -> bool:
214
+ environment = os.environ.copy()
215
+ environment["GIT_OPTIONAL_LOCKS"] = "0"
216
+ result = run(
217
+ ("git", "-C", str(repo), "status", "--porcelain=v1", "--untracked-files=all"),
218
+ env=environment,
219
+ )
220
+ if result.returncode != 0:
221
+ detail = result.stderr.strip() or result.stdout.strip() or "unknown git error"
222
+ raise SyncError(f"git status failed for {repo}: {detail}")
223
+ return bool(result.stdout.strip())
224
+
225
+
226
+ def project_version(repo: Path, tool_name: str, *, kind: str | None = None) -> tuple[str, tuple[str, ...]]:
227
+ pyproject = repo / "pyproject.toml"
228
+ use_pyproject = kind == "python_console_scripts" or (
229
+ kind is None and tool_name in {"context-loader", "snapshot-runner", "git-finalizer"} and pyproject.is_file()
230
+ )
231
+ if use_pyproject:
232
+ require_regular(pyproject, "project metadata")
233
+ with pyproject.open("rb") as stream:
234
+ data = tomllib.load(stream)
235
+ version = data.get("project", {}).get("version")
236
+ scripts = data.get("project", {}).get("scripts", {})
237
+ if not isinstance(version, str) or not isinstance(scripts, dict):
238
+ raise SyncError(f"invalid project version/scripts: {pyproject}")
239
+ return version, tuple(sorted(str(name) for name in scripts))
240
+
241
+ manifest_candidates = (
242
+ repo / "tool_skill_manifest.json",
243
+ repo / "manifests" / tool_name / "tool_skill_manifest.json",
244
+ )
245
+ manifest_path = next((p for p in manifest_candidates if p.exists()), manifest_candidates[0])
246
+ manifest = read_json(manifest_path)
247
+ entrypoints = validate_install_targets(manifest)
248
+ if manifest["executable"]["kind"] == "python_console_scripts":
249
+ return project_version(repo, tool_name, kind="python_console_scripts")
250
+ executable = repo / entrypoints[0]
251
+ require_regular(executable, "Git Finalizer executable")
252
+ match = re.search(
253
+ rb"(?m)^(?:readonly )?(?:VERSION|__version__)\s*=\s*['\"]([0-9]+\.[0-9]+\.[0-9]+)['\"]$",
254
+ executable.read_bytes(),
255
+ )
256
+ if match is None:
257
+ raise SyncError("cannot read source version")
258
+ return match.group(1).decode(), tuple(sorted(entrypoints))
259
+
260
+
261
+ class Sources:
262
+ def __init__(
263
+ self, source_root: Path, source_repos: dict[str, Path] | None = None,
264
+ source_refs: dict[str, str] | None = None,
265
+ ) -> None:
266
+ self.source_root = source_root.resolve()
267
+ self.source_refs = dict(source_refs or {})
268
+ self.source_repos = {
269
+ name: path.resolve() for name, path in (source_repos or {}).items()
270
+ }
271
+ self.owner_repo = self.source_repos.get(
272
+ "git-finalizer", self.source_root / "git-finalizer"
273
+ )
274
+ require_owned_directory(self.owner_repo)
275
+ self.compatibility_path = self.owner_repo / "toolchain_compatibility.json"
276
+ self.compatibility = read_json(self.compatibility_path)
277
+ if self.compatibility.get("schema_version") != SCHEMA_VERSION:
278
+ raise SyncError("unsupported toolchain compatibility schema_version")
279
+ workflow_skill = self.compatibility.get("workflow_skill")
280
+ if workflow_skill != {
281
+ "name": SKILL_NAME,
282
+ "contract_version": workflow_skill.get("contract_version")
283
+ if isinstance(workflow_skill, dict) else None,
284
+ "canonical_owner": "git-finalizer",
285
+ "compatibility_shims": [COMPATIBILITY_SKILL_NAME],
286
+ }:
287
+ raise SyncError("toolchain workflow Skill binding is unrecognized")
288
+ if workflow_skill["contract_version"] not in {1, 2}:
289
+ raise SyncError("unsupported workflow Skill contract version")
290
+ tools = self.compatibility.get("tools")
291
+ if not isinstance(tools, dict) or not tools:
292
+ raise SyncError("toolchain compatibility contract has no tools")
293
+ self.tool_config = tools
294
+ if (set(self.source_repos) | set(self.source_refs)) - set(tools):
295
+ raise SyncError("source-repo names an unknown tool")
296
+ self.skill_root = self.owner_repo / "skills" / SKILL_NAME
297
+ self.compatibility_skill_root = (
298
+ self.owner_repo / "skills" / COMPATIBILITY_SKILL_NAME
299
+ )
300
+
301
+ def head(self, tool: str) -> str:
302
+ return self.source_refs.get(tool) or git_head(self.repo(tool))
303
+
304
+ def dirty(self, tool: str) -> bool:
305
+ return False if tool in self.source_refs else git_dirty(self.repo(tool))
306
+
307
+ def source_bytes(self, tool: str, relative: str) -> bytes:
308
+ repo = self.repo(tool)
309
+ if tool not in self.source_refs:
310
+ return (repo / relative).read_bytes()
311
+ if relative not in {"pyproject.toml", "tool_cli_contract.json"}:
312
+ raise SyncError("pinned source reads are limited to package metadata and contract")
313
+ oid = self.source_refs[tool]
314
+ if not FULL_GIT_OID.fullmatch(oid):
315
+ raise SyncError("source-ref requires a full commit OID")
316
+ manifest = read_json(self.manifest_path(tool))
317
+ if manifest["executable"]["kind"] != "python_console_scripts":
318
+ raise SyncError("source-ref only supports released Python console-script metadata")
319
+ if git(repo, "rev-parse", f"{oid}^{{commit}}") != oid:
320
+ raise SyncError("source-ref must identify a commit, not a tag object")
321
+ result = subprocess.run(
322
+ ["git", "-C", str(repo), "show", f"{oid}:{relative}"],
323
+ capture_output=True, check=False, timeout=30,
324
+ )
325
+ if result.returncode:
326
+ raise SyncError(f"pinned source file is unavailable: {tool}/{relative}")
327
+ return result.stdout
328
+
329
+ def project_identity(self, tool: str, *, kind: str | None = None) -> tuple[str, tuple[str, ...]]:
330
+ if tool not in self.source_refs:
331
+ return project_version(self.repo(tool), tool, kind=kind)
332
+ data = tomllib.loads(self.source_bytes(tool, "pyproject.toml").decode())
333
+ return data["project"]["version"], tuple(sorted(data["project"]["scripts"]))
334
+
335
+ def names(self) -> tuple[str, ...]:
336
+ return tuple(sorted(self.tool_config))
337
+
338
+ def repo(self, tool: str) -> Path:
339
+ config = self.tool_config.get(tool)
340
+ if not isinstance(config, dict):
341
+ raise SyncError(f"unknown tool: {tool}")
342
+ if tool in self.source_repos:
343
+ repo = self.source_repos[tool]
344
+ require_owned_directory(repo)
345
+ return repo
346
+ source_directory = config.get("source_directory")
347
+ if not isinstance(source_directory, str) or not SAFE_NAME.fullmatch(
348
+ source_directory
349
+ ):
350
+ raise SyncError(f"unsafe source directory for {tool}")
351
+ repo = (self.source_root / source_directory).resolve()
352
+ if repo.parent != self.source_root:
353
+ raise SyncError(f"source directory escapes source root for {tool}")
354
+ require_owned_directory(repo)
355
+ return repo
356
+
357
+ def manifest_path(self, tool: str) -> Path:
358
+ config = self.tool_config.get(tool, {})
359
+ manifest_rel = config.get("skill_manifest")
360
+ if manifest_rel:
361
+ return (self.owner_repo / manifest_rel).resolve()
362
+ repo = self.repo(tool)
363
+ repo_manifest = repo / "tool_skill_manifest.json"
364
+ if repo_manifest.exists():
365
+ return repo_manifest
366
+ internal_manifest = (
367
+ self.owner_repo / "manifests" / tool / "tool_skill_manifest.json"
368
+ )
369
+ if internal_manifest.exists():
370
+ return internal_manifest
371
+ return repo_manifest
372
+
373
+
374
+ def validate_install_targets(
375
+ manifest: dict[str, Any], *, allow_legacy: bool = False
376
+ ) -> tuple[str, ...]:
377
+ executable = manifest.get("executable")
378
+ install_targets = manifest.get("install_targets")
379
+ if not isinstance(executable, dict) or not isinstance(install_targets, dict):
380
+ raise SyncError("manifest executable/install_targets must be objects")
381
+ kind = executable.get("kind")
382
+ if kind not in {"python_console_scripts", "source_files"}:
383
+ raise SyncError(f"unsupported executable kind: {kind}")
384
+ entrypoints = executable.get("entrypoints")
385
+ stable_entries = install_targets.get("stable_entries")
386
+ if (
387
+ not isinstance(entrypoints, list)
388
+ or not entrypoints
389
+ or not isinstance(stable_entries, list)
390
+ or tuple(entrypoints) != tuple(stable_entries)
391
+ ):
392
+ raise SyncError("manifest entrypoints and stable_entries must match")
393
+ if any(
394
+ not isinstance(name, str) or not SAFE_NAME.fullmatch(name)
395
+ for name in entrypoints
396
+ ):
397
+ raise SyncError("manifest contains unsafe entrypoint")
398
+ expected_skill = SKILL_NAME
399
+ if allow_legacy and manifest.get("schema_version") == 1:
400
+ expected_skill = COMPATIBILITY_SKILL_NAME
401
+ if install_targets.get("skill_directory") != expected_skill:
402
+ raise SyncError("manifest has unrecognized Skill install target")
403
+ if kind == "source_files":
404
+ paths = executable.get("paths")
405
+ if not isinstance(paths, list) or not paths:
406
+ raise SyncError("source_files executable requires paths")
407
+ if any(
408
+ not isinstance(path, str)
409
+ or Path(path).is_absolute()
410
+ or ".." in Path(path).parts
411
+ for path in paths
412
+ ):
413
+ raise SyncError("manifest contains unsafe executable source path")
414
+ production_targets = executable.get("production_targets")
415
+ if not isinstance(production_targets, dict) or set(production_targets) != set(
416
+ paths
417
+ ):
418
+ raise SyncError(
419
+ "source_files executable requires one production target per path"
420
+ )
421
+ for relative in production_targets.values():
422
+ if (
423
+ not isinstance(relative, str)
424
+ or Path(relative).is_absolute()
425
+ or ".." in Path(relative).parts
426
+ or not Path(relative).parts
427
+ or Path(relative).parts[0] not in {"bin", "hooks"}
428
+ ):
429
+ raise SyncError("manifest contains unsafe production target")
430
+ elif "production_targets" in executable:
431
+ raise SyncError("python_console_scripts must not declare production targets")
432
+ return tuple(str(name) for name in entrypoints)
433
+
434
+
435
+ def validate_contract_shape(contract: dict[str, Any]) -> None:
436
+ commands = contract.get("commands")
437
+ operation_classes = contract.get("operation_classes")
438
+ protected_operations = contract.get("protected_operations")
439
+ if not isinstance(commands, list) or not commands:
440
+ raise SyncError("public CLI contract must contain commands")
441
+ if not isinstance(operation_classes, list) or not operation_classes:
442
+ raise SyncError("public CLI contract must contain operation_classes")
443
+ if not isinstance(protected_operations, list):
444
+ raise SyncError("public CLI contract protected_operations must be a list")
445
+ allowed_classes = {"read_only", "local_mutation", "remote_mutation"}
446
+ if not set(operation_classes) <= allowed_classes:
447
+ raise SyncError("public CLI contract has an unknown operation_class")
448
+ names: set[str] = set()
449
+ for command in commands:
450
+ if not isinstance(command, dict):
451
+ raise SyncError("public CLI contract command must be an object")
452
+ name = command.get("name")
453
+ if not isinstance(name, str) or not SAFE_NAME.fullmatch(name) or name in names:
454
+ raise SyncError("public CLI contract command name is invalid or duplicated")
455
+ names.add(name)
456
+ if command.get("operation_class") not in operation_classes:
457
+ raise SyncError("command operation_class is not declared")
458
+ for key in ("flags", "preconditions", "result_statuses"):
459
+ if not isinstance(command.get(key), list):
460
+ raise SyncError(f"public CLI contract command {key} must be a list")
461
+
462
+
463
+ def validate_manifest_static_fields(
464
+ manifest: dict[str, Any], *, allow_legacy: bool = False
465
+ ) -> None:
466
+ required = {
467
+ "schema_version",
468
+ "tool_name",
469
+ "tool_version",
470
+ "tool_commit",
471
+ "skill_contract_version",
472
+ "public_cli_contract_sha256",
473
+ "canonical_skill_sha256",
474
+ "compatible_toolchain_contract_version",
475
+ "canonical_skill",
476
+ "executable",
477
+ "install_targets",
478
+ }
479
+ legacy = allow_legacy and manifest.get("schema_version") == 1
480
+ if not legacy:
481
+ required.add("compatibility_skill")
482
+ if set(manifest) != required:
483
+ raise SyncError("ToolSkillManifest fields do not match its schema")
484
+ for key in ("public_cli_contract_sha256", "canonical_skill_sha256"):
485
+ if not isinstance(manifest.get(key), str) or not HEX_SHA256.fullmatch(
486
+ manifest[key]
487
+ ):
488
+ raise SyncError(f"ToolSkillManifest {key} is not SHA-256")
489
+ expected_name = COMPATIBILITY_SKILL_NAME if legacy else SKILL_NAME
490
+ canonical_skill = manifest.get("canonical_skill")
491
+ if canonical_skill != {
492
+ "owner": "git-finalizer",
493
+ "path": f"skills/{expected_name}/SKILL.md",
494
+ }:
495
+ raise SyncError("ToolSkillManifest canonical Skill authority is unrecognized")
496
+ if legacy:
497
+ return
498
+ compatibility_skill = manifest.get("compatibility_skill")
499
+ if (
500
+ not isinstance(compatibility_skill, dict)
501
+ or set(compatibility_skill) != {"name", "path", "sha256"}
502
+ or compatibility_skill.get("name") != COMPATIBILITY_SKILL_NAME
503
+ or compatibility_skill.get("path")
504
+ != f"skills/{COMPATIBILITY_SKILL_NAME}/SKILL.md"
505
+ ):
506
+ raise SyncError("ToolSkillManifest compatibility Skill binding is invalid")
507
+ digest = compatibility_skill.get("sha256")
508
+ if not isinstance(digest, str) or not HEX_SHA256.fullmatch(digest):
509
+ raise SyncError("ToolSkillManifest compatibility Skill SHA is invalid")
510
+
511
+
512
+ def validate_controller_requirements(requirements: Any) -> None:
513
+ keys = {"cli_contract_versions", "storage_layout_versions", "capability_versions"}
514
+ if not isinstance(requirements, dict) or set(requirements) != keys:
515
+ raise SyncError("missing or malformed reviewed Controller runtime requirements")
516
+ for key in ("cli_contract_versions", "storage_layout_versions"):
517
+ values = requirements[key]
518
+ if (not isinstance(values, list) or not values
519
+ or any(type(value) is not int or value <= 0 for value in values)
520
+ or len(set(values)) != len(values)):
521
+ raise SyncError(f"invalid Controller {key}")
522
+ capabilities = requirements["capability_versions"]
523
+ if not isinstance(capabilities, dict) or "capabilities_version" not in capabilities:
524
+ raise SyncError("Controller capability_versions must bind capabilities_version")
525
+ for name, value in capabilities.items():
526
+ if (not isinstance(name, str) or not re.fullmatch(r"[a-z][a-z0-9_]*_version", name)
527
+ or type(value) is not int or value <= 0):
528
+ raise SyncError("invalid Controller capability version binding")
529
+
530
+
531
+ def check_tool(sources: Sources, tool: str) -> dict[str, Any]:
532
+ errors: list[str] = []
533
+ repo = sources.repo(tool)
534
+ manifest_path = sources.manifest_path(tool)
535
+ try:
536
+ manifest = read_json(manifest_path)
537
+ raw_contract = sources.source_bytes(tool, "tool_cli_contract.json")
538
+ contract = json.loads(raw_contract.decode("utf-8"))
539
+ if not isinstance(contract, dict) or canonical_json(contract) != raw_contract:
540
+ raise SyncError("source contract is not deterministically serialized")
541
+ if manifest.get("schema_version") != TOOL_SKILL_MANIFEST_SCHEMA_VERSION:
542
+ raise SyncError("unsupported ToolSkillManifest schema_version")
543
+ if contract.get("schema_version") != SCHEMA_VERSION:
544
+ raise SyncError("unsupported public CLI contract schema_version")
545
+ if manifest.get("tool_name") != tool or contract.get("tool_name") != tool:
546
+ raise SyncError("tool_name mismatch")
547
+ validate_manifest_static_fields(manifest)
548
+ validate_contract_shape(contract)
549
+ if manifest.get("tool_version") != contract.get("tool_version"):
550
+ raise SyncError("tool version mismatch between manifest and CLI contract")
551
+ source_version, source_entrypoints = sources.project_identity(
552
+ tool, kind=manifest.get("executable", {}).get("kind")
553
+ )
554
+ if source_version != manifest.get("tool_version"):
555
+ raise SyncError("source version does not match ToolSkillManifest")
556
+ entrypoints = validate_install_targets(manifest)
557
+ if tuple(sorted(entrypoints)) != source_entrypoints:
558
+ raise SyncError("source public entrypoints do not match ToolSkillManifest")
559
+ if manifest.get("tool_commit") != "@release":
560
+ raise SyncError("canonical source manifest tool_commit must be @release")
561
+ sources.head(tool)
562
+ contract_sha = sha256_bytes(raw_contract)
563
+ if manifest.get("public_cli_contract_sha256") != contract_sha:
564
+ raise SyncError("public CLI contract SHA mismatch")
565
+ skill_sha = tree_sha256(sources.skill_root, SKILL_PAYLOAD)
566
+ if manifest.get("canonical_skill_sha256") != skill_sha:
567
+ raise SyncError("canonical Skill payload SHA mismatch")
568
+ compatibility_sha = sha256_file(sources.compatibility_skill_root / "SKILL.md")
569
+ if manifest["compatibility_skill"]["sha256"] != compatibility_sha:
570
+ raise SyncError("compatibility Skill SHA mismatch")
571
+ compatibility_version = sources.compatibility.get("toolchain_contract_version")
572
+ if compatibility_version not in {1, 2, 3, 4, 5, 6}:
573
+ raise SyncError("unsupported toolchain compatibility contract version")
574
+ if compatibility_version == 6:
575
+ runtime_requirements = sources.compatibility.get("runtime_requirements")
576
+ if not isinstance(runtime_requirements, dict):
577
+ raise SyncError("v6 requires explicit runtime_requirements")
578
+ validate_controller_requirements(runtime_requirements.get("worktree-controller"))
579
+ if (
580
+ manifest.get("compatible_toolchain_contract_version")
581
+ != compatibility_version
582
+ ):
583
+ raise SyncError("toolchain compatibility version mismatch")
584
+ config = sources.tool_config[tool]
585
+ if contract.get("contract_version") != config.get(
586
+ "public_cli_contract_version"
587
+ ):
588
+ raise SyncError("public contract version is incompatible with workflow")
589
+ compatibility_key = tool.replace("-", "_") + "_contract_version"
590
+ if sources.compatibility.get(compatibility_key) != config.get(
591
+ "public_cli_contract_version"
592
+ ):
593
+ raise SyncError("top-level toolchain contract binding is inconsistent")
594
+ if manifest.get("skill_contract_version") != config.get(
595
+ "skill_contract_version"
596
+ ):
597
+ raise SyncError("Skill contract version is incompatible with workflow")
598
+ controller_adapter = sources.compatibility.get(
599
+ "worktree_controller_adapter_version"
600
+ )
601
+ controller_status = sources.compatibility.get("worktree_controller_status")
602
+ if compatibility_version == 1:
603
+ if (
604
+ controller_adapter is not None
605
+ or controller_status != "planned_unavailable"
606
+ ):
607
+ raise SyncError(
608
+ "v1 requires Worktree Controller contract to remain null/planned"
609
+ )
610
+ elif (
611
+ controller_adapter
612
+ != (3 if compatibility_version >= 5 else 2 if compatibility_version >= 4 else 1)
613
+ or controller_status != "available_external"
614
+ ):
615
+ raise SyncError(
616
+ "external Worktree Controller contract is incompatible with the toolchain"
617
+ )
618
+ except (OSError, UnicodeError, ValueError, KeyError, TypeError, SyncError) as exc:
619
+ errors.append(str(exc))
620
+ manifest = {}
621
+ contract_sha = None
622
+ skill_sha = None
623
+
624
+ return {
625
+ "tool": tool,
626
+ "status": "PASS" if not errors else "FAIL",
627
+ "canonical_commit": sources.head(tool),
628
+ "canonical_source_dirty": sources.dirty(tool),
629
+ "source_selection": "pinned_commit" if tool in sources.source_refs else "working_checkout",
630
+ "source_checkout_dirty": git_dirty(repo),
631
+ "canonical_tool_version": manifest.get("tool_version"),
632
+ "canonical_skill_sha256": skill_sha,
633
+ "public_cli_contract_sha256": contract_sha,
634
+ "errors": errors,
635
+ }
636
+
637
+
638
+ def extract_version(output: str) -> str | None:
639
+ matches = re.findall(r"(?<![0-9])([0-9]+\.[0-9]+\.[0-9]+)(?![0-9])", output)
640
+ return matches[-1] if matches else None
641
+
642
+
643
+ def bundled_sync_version(bundle: Path) -> str:
644
+ candidates = (
645
+ bundle / "executable" / "src" / "git_finalizer" / "toolchain" / "tool_skill_sync.py",
646
+ bundle / "executable" / "tooling" / "tool_skill_sync.py",
647
+ )
648
+ implementation = next((p for p in candidates if p.exists() or p.is_symlink()), candidates[0])
649
+ require_regular(implementation, "bundled tool-skill-sync implementation")
650
+ try:
651
+ tree = ast.parse(implementation.read_text(encoding="utf-8"), filename=str(implementation))
652
+ except (SyntaxError, UnicodeDecodeError) as exc:
653
+ raise SyncError(f"bundled tool-skill-sync implementation is unparseable: {exc}") from exc
654
+ versions: list[str] = []
655
+ for node in tree.body:
656
+ if isinstance(node, ast.Assign):
657
+ targets = [t.id for t in node.targets if isinstance(t, ast.Name)]
658
+ value = node.value
659
+ elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name):
660
+ targets = [node.target.id]
661
+ value = node.value
662
+ else:
663
+ continue
664
+ if (
665
+ "VERSION" in targets
666
+ and isinstance(value, ast.Constant)
667
+ and isinstance(value.value, str)
668
+ and VERSION_LITERAL_RE.fullmatch(value.value)
669
+ ):
670
+ versions.append(value.value)
671
+ if len(versions) != 1:
672
+ raise SyncError("bundled tool-skill-sync VERSION constant is missing or ambiguous")
673
+ return versions[0]
674
+
675
+
676
+ def resolve_entry(name: str, bin_dir: Path | None) -> Path | None:
677
+ if bin_dir is not None:
678
+ candidate = bin_dir / name
679
+ return candidate.resolve() if candidate.exists() else None
680
+ resolved = shutil.which(name)
681
+ return Path(resolved).resolve() if resolved else None
682
+
683
+
684
+ def installed_binary_state(
685
+ entrypoints: Sequence[str], bin_dir: Path | None
686
+ ) -> dict[str, Any]:
687
+ entries: dict[str, dict[str, str | None]] = {}
688
+ hashes: dict[str, str] = {}
689
+ versions: set[str] = set()
690
+ complete = True
691
+ for entrypoint in entrypoints:
692
+ path = resolve_entry(entrypoint, bin_dir)
693
+ if path is None or path.is_symlink() or not path.is_file():
694
+ entries[entrypoint] = {
695
+ "path": str(path) if path else None,
696
+ "sha256": None,
697
+ "version": None,
698
+ }
699
+ complete = False
700
+ continue
701
+ digest = sha256_file(path)
702
+ environment = os.environ.copy()
703
+ environment["PYTHONDONTWRITEBYTECODE"] = "1"
704
+ environment["GIT_OPTIONAL_LOCKS"] = "0"
705
+ result = run((str(path), "--version"), env=environment)
706
+ version = (
707
+ extract_version(result.stdout + "\n" + result.stderr)
708
+ if result.returncode == 0
709
+ else None
710
+ )
711
+ if version is None:
712
+ complete = False
713
+ else:
714
+ versions.add(version)
715
+ hashes[entrypoint] = digest
716
+ entries[entrypoint] = {"path": str(path), "sha256": digest, "version": version}
717
+ installed_version = (
718
+ next(iter(versions)) if complete and len(versions) == 1 else None
719
+ )
720
+ return {
721
+ "version": installed_version,
722
+ "sha256": aggregate_hash(hashes) if complete else None,
723
+ "entries": entries,
724
+ }
725
+
726
+
727
+ def check_tool_deployment(
728
+ sources: Sources,
729
+ tool: str,
730
+ agents_root: Path,
731
+ bin_dir: Path | None,
732
+ hooks_dir: Path | None = None,
733
+ ) -> dict[str, Any]:
734
+ """Validate the source contract and the installed production state together.
735
+
736
+ ``source_contract_status`` keeps the original meaning: the canonical source repo is
737
+ internally consistent. ``installed_drift`` reports whether the executables actually on
738
+ PATH match the declared canonical release. ``status`` is PASS only when both hold, so
739
+ a stale or mismatched installation can no longer be reported as clean.
740
+ """
741
+ checked = check_tool(sources, tool)
742
+ source_status = str(checked["status"])
743
+ installed_skill_sha, installed_compatibility_sha = installed_skill_hashes(
744
+ agents_root
745
+ )
746
+ errors = list(checked["errors"])
747
+ binary: dict[str, Any] = {"version": None, "sha256": None, "entries": {}}
748
+ drift = "unknown"
749
+ verification: dict[str, Any] = {}
750
+ try:
751
+ manifest = read_json(sources.manifest_path(tool))
752
+ entrypoints = validate_install_targets(manifest)
753
+ binary = installed_binary_state(entrypoints, bin_dir)
754
+ drift = classify_drift(
755
+ manifest,
756
+ source_status=source_status,
757
+ binary_version=binary["version"],
758
+ installed_skill_sha=installed_skill_sha,
759
+ installed_compatibility_sha=installed_compatibility_sha,
760
+ )
761
+ if drift != "none":
762
+ errors.append(
763
+ f"installed production state drifts from the canonical release: {drift}"
764
+ )
765
+ verification = verify_installed_tool_bytes(
766
+ sources, tool, manifest, entrypoints, bin_dir,
767
+ hooks_dir or agents_root / "hooks",
768
+ )
769
+ if verification.get("binary_content_drift"):
770
+ raise SyncError("installed executable/sidecar bytes differ from source")
771
+ except (OSError, ValueError, KeyError, SyncError) as exc:
772
+ errors.append(str(exc))
773
+ if drift == "none":
774
+ drift = "binary_only"
775
+
776
+ result = dict(checked)
777
+ result["source_contract_status"] = source_status
778
+ result["installed_binary_version"] = binary["version"]
779
+ result["installed_binary_sha256"] = binary["sha256"]
780
+ result["installed_binaries"] = binary["entries"]
781
+ result["installed_skill_sha256"] = installed_skill_sha
782
+ result["installed_compatibility_skill_sha256"] = installed_compatibility_sha
783
+ result["installed_drift"] = drift
784
+ result.update(verification)
785
+ result["errors"] = errors
786
+ result["status"] = "PASS" if not errors and source_status == "PASS" and drift == "none" else "FAIL"
787
+ return result
788
+
789
+
790
+ def verify_installed_tool_bytes(
791
+ sources: Sources, tool: str, manifest: dict[str, Any],
792
+ entrypoints: Sequence[str], bin_dir: Path | None, hooks_dir: Path,
793
+ ) -> dict[str, Any]:
794
+ """One read-only artifact check shared by check and doctor."""
795
+ executable = manifest["executable"]
796
+ if executable["kind"] == "python_console_scripts":
797
+ installation = python_tool_installation(entrypoints, bin_dir)
798
+ return {"artifact_verification": verify_installed_record(Path(installation["root"]))}
799
+ first = resolve_entry(entrypoints[0], bin_dir)
800
+ if first is None:
801
+ raise SyncError(f"entrypoint is missing: {entrypoints[0]}")
802
+ live_bin = bin_dir or first.parent
803
+ drift = []
804
+ for relative, target in executable["production_targets"].items():
805
+ parts = Path(target).parts
806
+ if parts[0] not in {"bin", "hooks"}:
807
+ raise SyncError(f"unsupported production target: {target}")
808
+ root = live_bin if parts[0] == "bin" else hooks_dir
809
+ live = root.joinpath(*parts[1:])
810
+ if not live.is_file() or sha256_file(live) != sha256_bytes(sources.source_bytes(tool, relative)):
811
+ drift.append(str(live))
812
+ return {"binary_content_drift": drift}
813
+
814
+
815
+ UV_EXECUTABLE = "uv"
816
+
817
+
818
+ def read_uv_receipt(root: Path) -> dict[str, Any]:
819
+ receipt = root / "uv-receipt.toml"
820
+ require_regular(receipt, "uv tool receipt")
821
+ with receipt.open("rb") as stream:
822
+ return tomllib.load(stream)
823
+
824
+
825
+ def python_tool_installation(
826
+ entrypoints: Sequence[str], bin_dir: Path | None
827
+ ) -> dict[str, Any]:
828
+ """Describe the uv tool installation that backs one tool's console scripts."""
829
+ resolved = {name: resolve_entry(name, bin_dir) for name in entrypoints}
830
+ missing = sorted(name for name, path in resolved.items() if path is None)
831
+ if missing:
832
+ raise SyncError(f"installed entrypoints are missing: {', '.join(missing)}")
833
+ # Retained legacy launchers deliberately live outside the uv tool directory and shim
834
+ # into it, so the uv root is the one directory that actually carries a uv receipt.
835
+ roots = set()
836
+ for path in resolved.values():
837
+ if path is None:
838
+ continue
839
+ for candidate in list(path.parents)[:3]:
840
+ if (candidate / "uv-receipt.toml").is_file():
841
+ roots.add(candidate)
842
+ break
843
+ if not roots:
844
+ raise SyncError(
845
+ "installed entrypoints do not resolve into a uv tool installation"
846
+ )
847
+ if len(roots) != 1:
848
+ raise SyncError("installed entrypoints resolve to more than one uv tool root")
849
+ root = roots.pop()
850
+ require_owned_directory(root)
851
+ receipt = read_uv_receipt(root)
852
+ tool_section = receipt.get("tool", {})
853
+ options = tool_section.get("options", {})
854
+ install_paths = {
855
+ entry["name"]: Path(entry["install-path"])
856
+ for entry in tool_section.get("entrypoints", [])
857
+ if isinstance(entry, dict) and "name" in entry and "install-path" in entry
858
+ }
859
+ if not set(entrypoints) <= set(install_paths):
860
+ raise SyncError("uv receipt does not cover every declared entrypoint")
861
+ directories = {path.parent for path in install_paths.values()}
862
+ if len(directories) != 1:
863
+ raise SyncError("uv receipt entrypoints span more than one bin directory")
864
+ indexes = [
865
+ item["url"]
866
+ for item in options.get("index", [])
867
+ if isinstance(item, dict) and isinstance(item.get("url"), str)
868
+ ]
869
+ return {
870
+ "root": str(root),
871
+ "bin_dir": str(directories.pop()),
872
+ "indexes": indexes,
873
+ "no_build": bool(options.get("no-build", False)),
874
+ "entry_targets": {
875
+ name: str(path) for name, path in sorted(install_paths.items())
876
+ },
877
+ "resolved": {
878
+ name: str(path)
879
+ for name, path in sorted(resolved.items())
880
+ if path is not None
881
+ },
882
+ }
883
+
884
+
885
+ def verify_installed_record(root: Path) -> dict[str, Any]:
886
+ """Verify installed runtime files against the published wheel RECORD."""
887
+ candidates = sorted(root.glob("lib/python*/site-packages"))
888
+ if len(candidates) != 1:
889
+ raise SyncError("uv tool installation has no single site-packages directory")
890
+ site_packages = candidates[0]
891
+ dist_infos = sorted(site_packages.glob("*.dist-info"))
892
+ if not dist_infos:
893
+ raise SyncError("uv tool installation has no dist-info directory")
894
+ verified = 0
895
+ for dist_info in dist_infos:
896
+ record = dist_info / "RECORD"
897
+ require_regular(record, "installed RECORD")
898
+ distribution_verified = 0
899
+ for line in record.read_text(encoding="utf-8").splitlines():
900
+ if not line:
901
+ continue
902
+ name, _, remainder = line.partition(",")
903
+ digest, _, _size = remainder.partition(",")
904
+ # Console scripts live outside site-packages and RECORD lists itself without a hash.
905
+ if not digest.startswith("sha256=") or name.startswith("../"):
906
+ continue
907
+ target = site_packages / name
908
+ if not target.is_file():
909
+ raise SyncError(f"installed file is missing: {name}")
910
+ expected = digest.split("=", 1)[1]
911
+ actual = (
912
+ base64.urlsafe_b64encode(hashlib.sha256(target.read_bytes()).digest())
913
+ .rstrip(b"=")
914
+ .decode()
915
+ )
916
+ if actual != expected:
917
+ raise SyncError(
918
+ f"installed file does not match the published artifact: {name}"
919
+ )
920
+ distribution_verified += 1
921
+ if not distribution_verified:
922
+ raise SyncError(f"installed RECORD verified no files: {dist_info.name}")
923
+ verified += distribution_verified
924
+ if len(dist_infos) == 1:
925
+ return {"dist_info": dist_infos[0].name, "verified_files": verified}
926
+ return {"dist_infos": [path.name for path in dist_infos], "verified_files": verified}
927
+
928
+
929
+ def install_python_tool(
930
+ tool: str,
931
+ version: str,
932
+ *,
933
+ bin_dir: str,
934
+ indexes: Sequence[str],
935
+ no_build: bool,
936
+ ) -> None:
937
+ """Install one pinned uv tool release, preserving the recorded installation shape.
938
+
939
+ ``--force`` is required: ``--reinstall`` removes the existing installation before it
940
+ validates entrypoint conflicts, which can leave production with no working CLI.
941
+ """
942
+ argv = [UV_EXECUTABLE, "tool", "install", "--force"]
943
+ if no_build:
944
+ argv.append("--no-build")
945
+ for index in indexes:
946
+ argv.extend(("--index", index))
947
+ argv.append(f"{tool}=={version}")
948
+ environment = dict(os.environ, UV_TOOL_BIN_DIR=bin_dir)
949
+ result = subprocess.run(
950
+ argv, capture_output=True, text=True, check=False, env=environment
951
+ )
952
+ if result.returncode:
953
+ raise SyncError(
954
+ f"uv tool install failed for {tool}=={version} "
955
+ f"(exit {result.returncode}): {result.stderr.strip()[:200]}"
956
+ )
957
+
958
+
959
+ def install_local_python_tool(
960
+ tool: str,
961
+ source_path: Path,
962
+ *,
963
+ bin_dir: str,
964
+ no_build: bool,
965
+ ) -> None:
966
+ """Install one tool offline from a verified local checkout or exported commit tree."""
967
+ argv = [UV_EXECUTABLE, "tool", "install", "--force", "--offline"]
968
+ if no_build:
969
+ argv.append("--no-build")
970
+ argv.append(os.fspath(source_path))
971
+ environment = dict(os.environ, UV_TOOL_BIN_DIR=bin_dir)
972
+ result = subprocess.run(
973
+ argv, capture_output=True, text=True, check=False, env=environment
974
+ )
975
+ if result.returncode:
976
+ raise SyncError(
977
+ f"uv tool offline install failed for {tool} "
978
+ f"(exit {result.returncode}): {result.stderr.strip()[:200]}"
979
+ )
980
+
981
+
982
+ def _resolves_into_python_venv(entry: Path) -> bool:
983
+ resolved = entry.resolve(strict=False)
984
+ return any((parent / "pyvenv.cfg").is_file() for parent in list(resolved.parents)[:3])
985
+
986
+
987
+ def _legacy_source_files_installation(
988
+ entrypoints: Sequence[str], bin_dir: Path | None
989
+ ) -> dict[str, Any] | None:
990
+ """Describe a legacy `source_files` install so 1.x -> 2.x wheel upgrade works cleanly."""
991
+ targets: dict[str, Path] = {}
992
+ dirs: set[Path] = set()
993
+ for name in entrypoints:
994
+ if bin_dir is not None:
995
+ candidate = bin_dir / name
996
+ else:
997
+ found = shutil.which(name)
998
+ if not found:
999
+ return None
1000
+ candidate = Path(found)
1001
+ if not candidate.exists() or _resolves_into_python_venv(candidate):
1002
+ return None
1003
+ targets[name] = candidate
1004
+ dirs.add(candidate.parent.resolve())
1005
+ if len(dirs) != 1:
1006
+ return None
1007
+ target_bin = dirs.pop()
1008
+ return {
1009
+ "root": None,
1010
+ "bin_dir": str(target_bin),
1011
+ "indexes": [],
1012
+ "no_build": False,
1013
+ "entry_targets": {},
1014
+ "resolved": {},
1015
+ "legacy_targets": {name: str(path) for name, path in sorted(targets.items())},
1016
+ "legacy_source_files": True,
1017
+ }
1018
+
1019
+
1020
+ def _backup_legacy_entries(entry_map: dict[str, str]) -> dict[Path, dict[str, Any]]:
1021
+ snapshot: dict[Path, dict[str, Any]] = {}
1022
+ for raw_path in entry_map.values():
1023
+ path = Path(raw_path)
1024
+ if path.is_symlink():
1025
+ snapshot[path] = {"symlink": os.readlink(path)}
1026
+ elif path.is_file():
1027
+ snapshot[path] = {
1028
+ "bytes": path.read_bytes(),
1029
+ "mode": stat.S_IMODE(path.stat().st_mode),
1030
+ }
1031
+ return snapshot
1032
+
1033
+
1034
+ def _restore_legacy_entries(snapshot: dict[Path, dict[str, Any]]) -> None:
1035
+ for path, info in snapshot.items():
1036
+ if "symlink" in info:
1037
+ atomic_symlink(path.parent, path.name, Path(info["symlink"]))
1038
+ continue
1039
+ fd, tmp_name = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.restore-")
1040
+ os.close(fd)
1041
+ tmp = Path(tmp_name)
1042
+ try:
1043
+ tmp.write_bytes(info["bytes"])
1044
+ tmp.chmod(info["mode"])
1045
+ os.replace(tmp, path)
1046
+ fsync_directory(path.parent)
1047
+ finally:
1048
+ if tmp.exists():
1049
+ tmp.unlink()
1050
+
1051
+
1052
+ @contextmanager
1053
+ def _local_install_source(sources: Sources, tool: str):
1054
+ repo = sources.repo(tool)
1055
+ if tool not in sources.source_refs:
1056
+ yield repo
1057
+ return
1058
+ oid = sources.source_refs[tool]
1059
+ if not FULL_GIT_OID.fullmatch(oid):
1060
+ raise SyncError("source-ref requires a full commit OID")
1061
+ with tempfile.TemporaryDirectory(prefix=f".{tool}-src-") as staging:
1062
+ archive = subprocess.run(
1063
+ ["git", "-C", str(repo), "archive", "--format=tar", oid],
1064
+ capture_output=True,
1065
+ check=False,
1066
+ timeout=30,
1067
+ )
1068
+ if archive.returncode:
1069
+ raise SyncError(f"git archive failed for pinned {tool}@{oid}")
1070
+ target_dir = Path(staging) / tool
1071
+ target_dir.mkdir(mode=0o700)
1072
+ with tarfile.open(fileobj=io.BytesIO(archive.stdout), mode="r:*") as tf:
1073
+ tf.extractall(target_dir, filter="data")
1074
+ yield target_dir
1075
+
1076
+
1077
+ def canonical_install_policy(
1078
+ sources: Sources, tool: str, observed: dict[str, Any]
1079
+ ) -> tuple[dict[str, Any], bool]:
1080
+ """Return the intended uv install shape and whether the observed receipt drifted.
1081
+
1082
+ ``uv_install_policy`` in the toolchain compatibility contract is authoritative when
1083
+ present, so a receipt that drifted away from the declared bin directory, package index
1084
+ or no-build policy is normalized instead of being preserved. Without a declared policy
1085
+ the observed receipt is kept, which is the previous behavior.
1086
+ """
1087
+ policy = sources.tool_config.get(tool, {}).get("uv_install_policy")
1088
+ if policy is None:
1089
+ return dict(observed), False
1090
+ if not isinstance(policy, dict):
1091
+ raise SyncError(f"{tool} uv_install_policy must be an object")
1092
+ bin_dir = policy.get("bin_dir")
1093
+ if not isinstance(bin_dir, str) or not bin_dir:
1094
+ raise SyncError(f"{tool} uv_install_policy bin_dir is invalid")
1095
+ resolved = Path(bin_dir).expanduser()
1096
+ if not resolved.is_absolute():
1097
+ raise SyncError(
1098
+ f"{tool} uv_install_policy bin_dir must resolve to an absolute path"
1099
+ )
1100
+ indexes = policy.get("index", [])
1101
+ if not isinstance(indexes, list) or not all(
1102
+ isinstance(item, str) and item for item in indexes
1103
+ ):
1104
+ raise SyncError(f"{tool} uv_install_policy index must be a list of URLs")
1105
+ intended = dict(observed)
1106
+ intended["bin_dir"] = os.fspath(resolved)
1107
+ intended["indexes"] = list(indexes)
1108
+ intended["no_build"] = bool(policy.get("no_build", False))
1109
+ drifted = (
1110
+ observed["bin_dir"] != intended["bin_dir"]
1111
+ or observed["no_build"] != intended["no_build"]
1112
+ or not set(intended["indexes"]) <= set(observed["indexes"])
1113
+ )
1114
+ return intended, drifted
1115
+
1116
+
1117
+ def verify_python_tool(
1118
+ tool: str,
1119
+ version: str,
1120
+ entrypoints: Sequence[str],
1121
+ bin_dir: Path | None,
1122
+ expected: dict[str, Any],
1123
+ *,
1124
+ expect_stable_paths: bool = True,
1125
+ ) -> dict[str, Any]:
1126
+ """Fail closed unless every entrypoint, hash and receipt field matches the release."""
1127
+ binary = installed_binary_state(entrypoints, bin_dir)
1128
+ if binary["version"] != version:
1129
+ raise SyncError(
1130
+ f"installed {tool} reports {binary['version']}, expected {version}"
1131
+ )
1132
+ installation = python_tool_installation(entrypoints, bin_dir)
1133
+ if installation["bin_dir"] != expected["bin_dir"]:
1134
+ raise SyncError("upgrade changed the entrypoint bin directory")
1135
+ if installation["no_build"] != expected["no_build"]:
1136
+ raise SyncError("upgrade changed the receipt no-build setting")
1137
+ if not set(expected["indexes"]) <= set(installation["indexes"]):
1138
+ raise SyncError("upgrade dropped a recorded package index")
1139
+ # A release may intentionally remove console scripts, so compare only the entrypoints
1140
+ # the target release declares. Retained entrypoints must keep their exact install path
1141
+ # and resolved target; entrypoints the new release drops are reported as retired.
1142
+ for name in entrypoints if expect_stable_paths else ():
1143
+ previous_target = expected["entry_targets"].get(name)
1144
+ if (
1145
+ previous_target is not None
1146
+ and installation["entry_targets"][name] != previous_target
1147
+ ):
1148
+ raise SyncError(f"upgrade changed the install path of {name}")
1149
+ previous_resolved = expected["resolved"].get(name)
1150
+ if (
1151
+ previous_resolved is not None
1152
+ and installation["resolved"][name] != previous_resolved
1153
+ ):
1154
+ raise SyncError(f"upgrade changed the resolved target of {name}")
1155
+ retired = sorted(set(expected["entry_targets"]) - set(entrypoints))
1156
+ for name in retired:
1157
+ path = Path(expected["entry_targets"][name])
1158
+ if path.exists() or path.is_symlink():
1159
+ raise SyncError(f"upgrade left a retired entrypoint installed: {name}")
1160
+ record = verify_installed_record(Path(installation["root"]))
1161
+ return {
1162
+ "version": binary["version"],
1163
+ "binary_sha256": binary["sha256"],
1164
+ "entries": binary["entries"],
1165
+ "installation": installation,
1166
+ "retired_entrypoints": retired,
1167
+ "record": record,
1168
+ }
1169
+
1170
+
1171
+ def upgrade(
1172
+ sources: Sources,
1173
+ tool: str,
1174
+ *,
1175
+ bin_dir: Path | None,
1176
+ dry_run: bool = False,
1177
+ previous_bundle: Path | None = None,
1178
+ ) -> dict[str, Any]:
1179
+ """Upgrade one console-script tool to its canonical release, or restore the old one."""
1180
+ checked = check_tool(sources, tool)
1181
+ if checked["status"] != "PASS":
1182
+ raise SyncError("canonical check failed: " + "; ".join(checked["errors"]))
1183
+ manifest = read_json(sources.manifest_path(tool))
1184
+ entrypoints = validate_install_targets(manifest)
1185
+ if manifest["executable"]["kind"] != "python_console_scripts":
1186
+ raise SyncError(f"{tool} is not installed as Python console scripts")
1187
+ target_version = str(manifest["tool_version"])
1188
+ previous_entries = entrypoints
1189
+ previous_manifest = None
1190
+ if previous_bundle is not None:
1191
+ verify_bundle(previous_bundle, tool)
1192
+ previous_manifest = read_json(previous_bundle / "tool_skill_manifest.json")
1193
+ if previous_manifest["executable"]["kind"] not in {"python_console_scripts", "source_files"}:
1194
+ raise SyncError("previous bundle is not a supported executable kind")
1195
+ previous_entries = validate_install_targets(previous_manifest, allow_legacy=True)
1196
+ if previous_manifest is not None and previous_manifest["executable"]["kind"] == "source_files":
1197
+ before = _legacy_source_files_installation(previous_entries, bin_dir)
1198
+ if before is None:
1199
+ raise SyncError("legacy source_files installation is incomplete or unavailable")
1200
+ else:
1201
+ try:
1202
+ before = python_tool_installation(previous_entries, bin_dir)
1203
+ except SyncError:
1204
+ legacy = (
1205
+ _legacy_source_files_installation(previous_entries, bin_dir)
1206
+ if previous_manifest is None
1207
+ else None
1208
+ )
1209
+ if legacy is None:
1210
+ raise
1211
+ before = legacy
1212
+ intended, drifted = canonical_install_policy(sources, tool, before)
1213
+ legacy_upgrade = bool(before.get("legacy_source_files"))
1214
+ previous_version = installed_binary_state(previous_entries, bin_dir)["version"]
1215
+ if previous_manifest is not None:
1216
+ if previous_version != previous_manifest["tool_version"]:
1217
+ raise SyncError("installed release does not match the explicit previous bundle")
1218
+ if not legacy_upgrade:
1219
+ verify_python_tool(tool, previous_version, previous_entries, bin_dir, before)
1220
+ stable_paths = intended["bin_dir"] == before["bin_dir"] and not legacy_upgrade
1221
+ plan = {
1222
+ "schema_version": SCHEMA_VERSION,
1223
+ "operation": "upgrade",
1224
+ "tool": tool,
1225
+ "previous_version": previous_version,
1226
+ "target_version": target_version,
1227
+ "bin_dir": intended["bin_dir"],
1228
+ "indexes": intended["indexes"],
1229
+ "no_build": intended["no_build"],
1230
+ "receipt_drifted": drifted,
1231
+ "observed_bin_dir": before["bin_dir"],
1232
+ "observed_no_build": before["no_build"],
1233
+ }
1234
+ if (
1235
+ not legacy_upgrade
1236
+ and previous_version == target_version
1237
+ and not drifted
1238
+ and previous_entries == entrypoints
1239
+ ):
1240
+ plan["status"] = "UNCHANGED"
1241
+ plan["verification"] = verify_python_tool(
1242
+ tool, target_version, entrypoints, bin_dir, intended
1243
+ )
1244
+ return plan
1245
+ if dry_run:
1246
+ plan["status"] = "DRY_RUN_NORMALIZE" if drifted else "DRY_RUN"
1247
+ return plan
1248
+ legacy_backup = (
1249
+ _backup_legacy_entries(before.get("legacy_targets", {})) if legacy_upgrade else None
1250
+ )
1251
+ try:
1252
+ if intended["indexes"]:
1253
+ install_python_tool(
1254
+ tool,
1255
+ target_version,
1256
+ bin_dir=intended["bin_dir"],
1257
+ indexes=intended["indexes"],
1258
+ no_build=intended["no_build"],
1259
+ )
1260
+ else:
1261
+ with _local_install_source(sources, tool) as local_source:
1262
+ install_local_python_tool(
1263
+ tool,
1264
+ local_source,
1265
+ bin_dir=intended["bin_dir"],
1266
+ no_build=intended["no_build"],
1267
+ )
1268
+ plan["verification"] = verify_python_tool(
1269
+ tool,
1270
+ target_version,
1271
+ entrypoints,
1272
+ bin_dir,
1273
+ intended,
1274
+ expect_stable_paths=stable_paths,
1275
+ )
1276
+ except (SyncError, OSError, subprocess.SubprocessError, KeyboardInterrupt) as exc:
1277
+ plan["status"] = "RESTORED"
1278
+ plan["error"] = str(exc)
1279
+ if legacy_backup is not None:
1280
+ try:
1281
+ _restore_legacy_entries(legacy_backup)
1282
+ plan["restored_shape"] = "legacy_source_files"
1283
+ except (SyncError, OSError, subprocess.SubprocessError) as restore_error:
1284
+ plan["status"] = "FAILED"
1285
+ raise SyncError(
1286
+ f"{exc}; restoring legacy {previous_version} also failed: {restore_error}"
1287
+ ) from None
1288
+ if isinstance(exc, KeyboardInterrupt):
1289
+ raise
1290
+ raise SyncError(
1291
+ f"upgrade failed and legacy {previous_version} was restored: {exc}"
1292
+ ) from None
1293
+ if previous_version is None:
1294
+ plan["status"] = "FAILED"
1295
+ raise SyncError(f"{exc}; no previous version recorded to restore") from None
1296
+ try:
1297
+ install_python_tool(
1298
+ tool,
1299
+ previous_version,
1300
+ bin_dir=before["bin_dir"],
1301
+ indexes=before["indexes"],
1302
+ no_build=before["no_build"],
1303
+ )
1304
+ plan["restored_verification"] = verify_python_tool(
1305
+ tool, previous_version, previous_entries, bin_dir, before
1306
+ )
1307
+ for name in set(entrypoints) - set(previous_entries):
1308
+ path = Path(intended["bin_dir"]) / name
1309
+ if path.exists() or path.is_symlink():
1310
+ raise SyncError(f"restoration left a new entrypoint installed: {name}")
1311
+ plan["restored_shape"] = "observed"
1312
+ except (SyncError, OSError, subprocess.SubprocessError) as restore_error:
1313
+ plan["status"] = "FAILED"
1314
+ raise SyncError(
1315
+ f"{exc}; restoring {previous_version} also failed: {restore_error}"
1316
+ ) from None
1317
+ if isinstance(exc, KeyboardInterrupt):
1318
+ raise
1319
+ raise SyncError(
1320
+ f"upgrade failed and {previous_version} was restored: {exc}"
1321
+ ) from None
1322
+ plan["status"] = (
1323
+ "NORMALIZED" if (not legacy_upgrade and previous_version == target_version) else "UPGRADED"
1324
+ )
1325
+ return plan
1326
+
1327
+
1328
+ def installed_skill_hashes(agents_root: Path) -> tuple[str | None, str | None]:
1329
+ """Return the installed canonical and compatibility Skill payload hashes."""
1330
+ try:
1331
+ skill_sha = tree_sha256(agents_root / "skills" / SKILL_NAME, SKILL_PAYLOAD)
1332
+ except SyncError:
1333
+ skill_sha = None
1334
+ compatibility = agents_root / "skills" / COMPATIBILITY_SKILL_NAME / "SKILL.md"
1335
+ try:
1336
+ require_regular(compatibility, "installed compatibility Skill")
1337
+ compatibility_sha = sha256_file(compatibility)
1338
+ except SyncError:
1339
+ compatibility_sha = None
1340
+ return skill_sha, compatibility_sha
1341
+
1342
+
1343
+ def classify_drift(
1344
+ manifest: dict[str, Any],
1345
+ *,
1346
+ source_status: str,
1347
+ binary_version: str | None,
1348
+ installed_skill_sha: str | None,
1349
+ installed_compatibility_sha: str | None,
1350
+ ) -> str:
1351
+ """Classify installed production state against the declared canonical release."""
1352
+ binary_matches = binary_version == manifest.get("tool_version")
1353
+ skill_matches = installed_skill_sha == manifest.get(
1354
+ "canonical_skill_sha256"
1355
+ ) and installed_compatibility_sha == manifest.get("compatibility_skill", {}).get(
1356
+ "sha256"
1357
+ )
1358
+ if source_status != "PASS" or (not binary_matches and not skill_matches):
1359
+ return "incompatible"
1360
+ if binary_matches and skill_matches:
1361
+ return "none"
1362
+ if binary_matches:
1363
+ return "skill_only"
1364
+ return "binary_only"
1365
+
1366
+
1367
+ def status(sources: Sources, agents_root: Path, bin_dir: Path | None) -> dict[str, Any]:
1368
+ result: dict[str, Any] = {
1369
+ "schema_version": SCHEMA_VERSION,
1370
+ "operation": "status",
1371
+ "tools": [],
1372
+ }
1373
+ installed_skill_sha, installed_compatibility_sha = installed_skill_hashes(
1374
+ agents_root
1375
+ )
1376
+
1377
+ for tool in sources.names():
1378
+ checked = check_tool(sources, tool)
1379
+ try:
1380
+ manifest = read_json(sources.manifest_path(tool))
1381
+ entrypoints = validate_install_targets(manifest)
1382
+ except SyncError:
1383
+ result["tools"].append(
1384
+ {
1385
+ "tool_name": tool,
1386
+ "canonical_tool_version": checked["canonical_tool_version"],
1387
+ "canonical_commit": checked["canonical_commit"],
1388
+ "canonical_source_dirty": checked["canonical_source_dirty"],
1389
+ "canonical_skill_sha256": checked["canonical_skill_sha256"],
1390
+ "public_cli_contract_sha256": checked["public_cli_contract_sha256"],
1391
+ "installed_binary_version": None,
1392
+ "installed_binary_sha256": None,
1393
+ "installed_binaries": {},
1394
+ "installed_skill_sha256": installed_skill_sha,
1395
+ "installed_compatibility_skill_sha256": (
1396
+ installed_compatibility_sha
1397
+ ),
1398
+ "drift": "incompatible",
1399
+ }
1400
+ )
1401
+ continue
1402
+ binary = installed_binary_state(entrypoints, bin_dir)
1403
+ drift = classify_drift(
1404
+ manifest,
1405
+ source_status=str(checked["status"]),
1406
+ binary_version=binary["version"],
1407
+ installed_skill_sha=installed_skill_sha,
1408
+ installed_compatibility_sha=installed_compatibility_sha,
1409
+ )
1410
+ result["tools"].append(
1411
+ {
1412
+ "tool_name": tool,
1413
+ "canonical_tool_version": manifest.get("tool_version"),
1414
+ "canonical_commit": sources.head(tool),
1415
+ "canonical_source_dirty": sources.dirty(tool),
1416
+ "canonical_skill_sha256": manifest.get("canonical_skill_sha256"),
1417
+ "public_cli_contract_sha256": manifest.get(
1418
+ "public_cli_contract_sha256"
1419
+ ),
1420
+ "installed_binary_version": binary["version"],
1421
+ "installed_binary_sha256": binary["sha256"],
1422
+ "installed_binaries": binary["entries"],
1423
+ "installed_skill_sha256": installed_skill_sha,
1424
+ "installed_compatibility_skill_sha256": installed_compatibility_sha,
1425
+ "drift": drift,
1426
+ }
1427
+ )
1428
+ return result
1429
+
1430
+
1431
+ def copy_skill_payload(source: Path, target: Path) -> None:
1432
+ for relative in SKILL_PAYLOAD:
1433
+ source_path = source / relative
1434
+ target_path = target / relative
1435
+ target_path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
1436
+ shutil.copyfile(source_path, target_path)
1437
+ target_path.chmod(0o600)
1438
+
1439
+
1440
+ def copy_compatibility_skill(source: Path, target: Path) -> None:
1441
+ source_path = source / "SKILL.md"
1442
+ require_regular(source_path, "compatibility Skill source")
1443
+ target_path = target / COMPATIBILITY_BUNDLE_PATH
1444
+ target_path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
1445
+ shutil.copyfile(source_path, target_path)
1446
+ target_path.chmod(0o600)
1447
+
1448
+
1449
+ def source_executable_payload(
1450
+ repo: Path,
1451
+ manifest: dict[str, Any],
1452
+ target: Path,
1453
+ tool_commit: str,
1454
+ ) -> tuple[str, dict[str, str]]:
1455
+ executable = manifest["executable"]
1456
+ kind = executable["kind"]
1457
+ if kind == "python_console_scripts":
1458
+ identity = {
1459
+ "schema_version": SCHEMA_VERSION,
1460
+ "kind": kind,
1461
+ "tool_name": manifest["tool_name"],
1462
+ "tool_version": manifest["tool_version"],
1463
+ "tool_commit": tool_commit,
1464
+ "entrypoints": executable["entrypoints"],
1465
+ }
1466
+ identity_path = target / "executable_identity.json"
1467
+ write_json(identity_path, identity)
1468
+ digest = sha256_file(identity_path)
1469
+ return digest, {"executable_identity.json": digest}
1470
+
1471
+ executable_root = target / "executable"
1472
+ executable_root.mkdir(mode=0o700)
1473
+ hashes: dict[str, str] = {}
1474
+ for relative in executable["paths"]:
1475
+ source_path = repo / relative
1476
+ require_regular(source_path, "executable source")
1477
+ target_path = executable_root / relative
1478
+ target_path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
1479
+ shutil.copyfile(source_path, target_path)
1480
+ target_path.chmod(stat.S_IMODE(source_path.stat().st_mode) & 0o755)
1481
+ hashes[f"executable/{relative}"] = sha256_file(target_path)
1482
+ return aggregate_hash(hashes), hashes
1483
+
1484
+
1485
+ def verify_bundle(bundle: Path, expected_tool: str | None = None) -> dict[str, Any]:
1486
+ require_owned_directory(bundle)
1487
+ release = read_json(bundle / "release_manifest.json")
1488
+ manifest = read_json(bundle / "tool_skill_manifest.json")
1489
+ contract = read_json(bundle / "tool_cli_contract.json")
1490
+ if release.get("schema_version") != SCHEMA_VERSION:
1491
+ raise SyncError("unsupported ToolReleaseBundle schema_version")
1492
+ if set(release) != {
1493
+ "schema_version",
1494
+ "tool_name",
1495
+ "tool_version",
1496
+ "tool_commit",
1497
+ "binary_or_entry_sha",
1498
+ "skill_sha",
1499
+ "cli_contract_sha",
1500
+ "manifest_sha",
1501
+ "source_state",
1502
+ }:
1503
+ raise SyncError(
1504
+ "ToolReleaseBundle release manifest fields do not match schema v1"
1505
+ )
1506
+ manifest_schema = manifest.get("schema_version")
1507
+ if manifest_schema not in {1, TOOL_SKILL_MANIFEST_SCHEMA_VERSION}:
1508
+ raise SyncError("unsupported bundled ToolSkillManifest schema_version")
1509
+ if contract.get("schema_version") != SCHEMA_VERSION:
1510
+ raise SyncError("unsupported bundled CLI contract schema_version")
1511
+ validate_manifest_static_fields(manifest, allow_legacy=True)
1512
+ validate_install_targets(manifest, allow_legacy=True)
1513
+ validate_contract_shape(contract)
1514
+ tool = release.get("tool_name")
1515
+ if expected_tool is not None and tool != expected_tool:
1516
+ raise SyncError("ToolReleaseBundle tool mismatch")
1517
+ if manifest.get("tool_name") != tool or contract.get("tool_name") != tool:
1518
+ raise SyncError("ToolReleaseBundle identity mismatch")
1519
+ if not (
1520
+ release.get("tool_version")
1521
+ == manifest.get("tool_version")
1522
+ == contract.get("tool_version")
1523
+ ):
1524
+ raise SyncError("ToolReleaseBundle version mismatch")
1525
+ if manifest.get("tool_commit") != release.get("tool_commit"):
1526
+ raise SyncError("ToolReleaseBundle commit mismatch")
1527
+ tool_commit = release.get("tool_commit")
1528
+ source_state = release.get("source_state")
1529
+ if source_state == "committed_release":
1530
+ if not isinstance(tool_commit, str) or not FULL_GIT_OID.fullmatch(tool_commit):
1531
+ raise SyncError("committed bundle does not bind a full Git OID")
1532
+ elif source_state == "dirty_test_only":
1533
+ if (
1534
+ not isinstance(tool_commit, str)
1535
+ or not tool_commit.startswith("worktree:")
1536
+ or not FULL_GIT_OID.fullmatch(tool_commit.removeprefix("worktree:"))
1537
+ ):
1538
+ raise SyncError("dirty test bundle has invalid worktree identity")
1539
+ else:
1540
+ raise SyncError("ToolReleaseBundle source_state is invalid")
1541
+ hashes = {
1542
+ "skill_sha": tree_sha256(bundle, SKILL_PAYLOAD),
1543
+ "cli_contract_sha": sha256_file(bundle / "tool_cli_contract.json"),
1544
+ "manifest_sha": sha256_file(bundle / "tool_skill_manifest.json"),
1545
+ }
1546
+ for key, value in hashes.items():
1547
+ if release.get(key) != value:
1548
+ raise SyncError(f"ToolReleaseBundle {key} mismatch")
1549
+ if manifest.get("canonical_skill_sha256") != hashes["skill_sha"]:
1550
+ raise SyncError("bundle Skill does not match ToolSkillManifest")
1551
+ if manifest_schema == TOOL_SKILL_MANIFEST_SCHEMA_VERSION:
1552
+ compatibility_path = bundle / COMPATIBILITY_BUNDLE_PATH
1553
+ require_regular(compatibility_path, "bundled compatibility Skill")
1554
+ if sha256_file(compatibility_path) != manifest["compatibility_skill"]["sha256"]:
1555
+ raise SyncError(
1556
+ "bundle compatibility Skill does not match ToolSkillManifest"
1557
+ )
1558
+ if manifest.get("public_cli_contract_sha256") != hashes["cli_contract_sha"]:
1559
+ raise SyncError("bundle CLI contract does not match ToolSkillManifest")
1560
+ executable = manifest.get("executable", {})
1561
+ if executable.get("kind") == "python_console_scripts":
1562
+ identity_path = bundle / "executable_identity.json"
1563
+ executable_hash = sha256_file(identity_path)
1564
+ elif executable.get("kind") == "source_files":
1565
+ file_hashes = {
1566
+ f"executable/{relative}": sha256_file(bundle / "executable" / relative)
1567
+ for relative in executable.get("paths", [])
1568
+ }
1569
+ executable_hash = aggregate_hash(file_hashes)
1570
+ else:
1571
+ raise SyncError("bundle executable kind is unsupported")
1572
+ if release.get("binary_or_entry_sha") != executable_hash:
1573
+ raise SyncError("ToolReleaseBundle executable identity mismatch")
1574
+ return release
1575
+
1576
+
1577
+ def smoke_bundle(bundle: Path) -> None:
1578
+ release = verify_bundle(bundle)
1579
+ manifest = read_json(bundle / "tool_skill_manifest.json")
1580
+ if manifest["executable"]["kind"] == "python_console_scripts":
1581
+ identity = read_json(bundle / "executable_identity.json")
1582
+ if identity.get("tool_version") != release.get("tool_version"):
1583
+ raise SyncError("entrypoint identity smoke failed")
1584
+ return
1585
+ entry = bundle / "executable" / manifest["executable"]["entrypoints"][0]
1586
+ result = run((str(entry), "--version"))
1587
+ if result.returncode != 0 or extract_version(
1588
+ result.stdout + result.stderr
1589
+ ) != release.get("tool_version"):
1590
+ raise SyncError("bundled executable --version smoke failed")
1591
+ sync_entry = bundle / "executable" / "tool-skill-sync"
1592
+ if sync_entry.exists():
1593
+ result = run((str(sync_entry), "--version"))
1594
+ if result.returncode != 0 or extract_version(
1595
+ result.stdout + result.stderr
1596
+ ) != bundled_sync_version(bundle):
1597
+ raise SyncError("bundled tool-skill-sync --version smoke failed")
1598
+
1599
+
1600
+ def atomic_symlink(directory: Path, name: str, target: Path) -> None:
1601
+ temporary = directory / f".{name}.{os.getpid()}"
1602
+ if temporary.exists() or temporary.is_symlink():
1603
+ temporary.unlink()
1604
+ relative = os.path.relpath(target, directory)
1605
+ os.symlink(relative, temporary)
1606
+ os.replace(temporary, directory / name)
1607
+ descriptor = os.open(directory, os.O_RDONLY)
1608
+ try:
1609
+ os.fsync(descriptor)
1610
+ finally:
1611
+ os.close(descriptor)
1612
+
1613
+
1614
+ def resolve_pointer(pointer: Path, bundles_root: Path) -> Path | None:
1615
+ if not pointer.exists() and not pointer.is_symlink():
1616
+ return None
1617
+ if not pointer.is_symlink():
1618
+ raise SyncError(f"bundle pointer is not a symlink: {pointer}")
1619
+ resolved = pointer.resolve(strict=True)
1620
+ try:
1621
+ resolved.relative_to(bundles_root.resolve())
1622
+ except ValueError as exc:
1623
+ raise SyncError(f"bundle pointer escapes managed root: {pointer}") from exc
1624
+ return resolved
1625
+
1626
+
1627
+ def fsync_directory(path: Path) -> None:
1628
+ descriptor = os.open(path, os.O_RDONLY)
1629
+ try:
1630
+ os.fsync(descriptor)
1631
+ finally:
1632
+ os.close(descriptor)
1633
+
1634
+
1635
+ def require_owned_regular(path: Path, label: str) -> None:
1636
+ require_regular(path, label)
1637
+ if path.stat().st_uid != os.getuid():
1638
+ raise SyncError(f"{label} is not owned by current user: {path}")
1639
+
1640
+
1641
+ def ensure_owned_subdirectory(root: Path, relative: Path) -> Path:
1642
+ require_owned_directory(root, create=True)
1643
+ current = root
1644
+ for part in relative.parts:
1645
+ if part in {"", ".", ".."}:
1646
+ raise SyncError(f"unsafe production directory component: {relative}")
1647
+ current /= part
1648
+ require_owned_directory(current, create=True)
1649
+ return current
1650
+
1651
+
1652
+ def production_target_sources(
1653
+ bundle: Path,
1654
+ *,
1655
+ agents_root: Path,
1656
+ bin_dir: Path | None,
1657
+ hooks_dir: Path,
1658
+ assert_installed_version: bool = True,
1659
+ ) -> tuple[dict[Path, Path], Path | None]:
1660
+ manifest = read_json(bundle / "tool_skill_manifest.json")
1661
+ entrypoints = validate_install_targets(manifest, allow_legacy=True)
1662
+ require_owned_directory(agents_root)
1663
+ skill_parent = ensure_owned_subdirectory(agents_root, Path("skills"))
1664
+ manifest_schema = manifest.get("schema_version")
1665
+ installed_skill_name = (
1666
+ COMPATIBILITY_SKILL_NAME if manifest_schema == 1 else SKILL_NAME
1667
+ )
1668
+ skill_root = ensure_owned_subdirectory(skill_parent, Path(installed_skill_name))
1669
+ targets: dict[Path, Path] = {}
1670
+ for skill_relative in SKILL_PAYLOAD:
1671
+ target = skill_root / skill_relative
1672
+ ensure_owned_subdirectory(skill_root, Path(skill_relative).parent)
1673
+ targets[target] = bundle / skill_relative
1674
+ if manifest_schema == TOOL_SKILL_MANIFEST_SCHEMA_VERSION:
1675
+ compatibility_root = ensure_owned_subdirectory(
1676
+ skill_parent, Path(COMPATIBILITY_SKILL_NAME)
1677
+ )
1678
+ compatibility_target = compatibility_root / "SKILL.md"
1679
+ targets[compatibility_target] = bundle / COMPATIBILITY_BUNDLE_PATH
1680
+
1681
+ executable = manifest["executable"]
1682
+ if executable["kind"] == "python_console_scripts":
1683
+ if assert_installed_version:
1684
+ binary = installed_binary_state(entrypoints, bin_dir)
1685
+ if binary["version"] != manifest["tool_version"]:
1686
+ raise SyncError(
1687
+ f"installed entrypoints do not match {manifest['tool_name']} "
1688
+ f"{manifest['tool_version']}"
1689
+ )
1690
+ return targets, bin_dir
1691
+
1692
+ if bin_dir is None:
1693
+ primary = resolve_entry(entrypoints[0], None)
1694
+ if primary is None:
1695
+ raise SyncError(f"stable entry is unavailable: {entrypoints[0]}")
1696
+ live_bin_dir = primary.parent
1697
+ else:
1698
+ live_bin_dir = bin_dir.resolve()
1699
+ require_owned_directory(live_bin_dir)
1700
+ roots = {"bin": live_bin_dir, "hooks": hooks_dir}
1701
+ for source_relative, target_relative in executable["production_targets"].items():
1702
+ target_path = Path(target_relative)
1703
+ root = roots[target_path.parts[0]]
1704
+ require_owned_directory(root)
1705
+ within_root = Path(*target_path.parts[1:])
1706
+ if not within_root.parts:
1707
+ raise SyncError("production target must name a file")
1708
+ ensure_owned_subdirectory(root, within_root.parent)
1709
+ target = root / within_root
1710
+ if target in targets:
1711
+ raise SyncError(f"duplicate production target: {target}")
1712
+ targets[target] = bundle / "executable" / source_relative
1713
+ return targets, live_bin_dir
1714
+
1715
+
1716
+ def verify_production_bundle(
1717
+ bundle: Path,
1718
+ *,
1719
+ agents_root: Path,
1720
+ bin_dir: Path | None,
1721
+ hooks_dir: Path,
1722
+ ) -> dict[str, Any]:
1723
+ release = verify_bundle(bundle)
1724
+ manifest = read_json(bundle / "tool_skill_manifest.json")
1725
+ targets, live_bin_dir = production_target_sources(
1726
+ bundle,
1727
+ agents_root=agents_root,
1728
+ bin_dir=bin_dir,
1729
+ hooks_dir=hooks_dir,
1730
+ )
1731
+ for target, source in targets.items():
1732
+ require_owned_regular(target, "active production target")
1733
+ if sha256_file(target) != sha256_file(source):
1734
+ raise SyncError(f"active production target SHA mismatch: {target}")
1735
+ manifest_schema = manifest.get("schema_version")
1736
+ installed_skill_name = (
1737
+ COMPATIBILITY_SKILL_NAME if manifest_schema == 1 else SKILL_NAME
1738
+ )
1739
+ if (
1740
+ tree_sha256(
1741
+ agents_root / "skills" / installed_skill_name,
1742
+ SKILL_PAYLOAD,
1743
+ )
1744
+ != release["skill_sha"]
1745
+ ):
1746
+ raise SyncError("active Skill SHA does not match ToolReleaseBundle")
1747
+ if manifest_schema == TOOL_SKILL_MANIFEST_SCHEMA_VERSION:
1748
+ compatibility_path = (
1749
+ agents_root / "skills" / COMPATIBILITY_SKILL_NAME / "SKILL.md"
1750
+ )
1751
+ require_owned_regular(compatibility_path, "active compatibility Skill")
1752
+ if sha256_file(compatibility_path) != manifest["compatibility_skill"]["sha256"]:
1753
+ raise SyncError("active compatibility Skill SHA does not match bundle")
1754
+
1755
+ entrypoints = validate_install_targets(manifest, allow_legacy=True)
1756
+ binary = installed_binary_state(entrypoints, live_bin_dir)
1757
+ if binary["version"] != release["tool_version"]:
1758
+ raise SyncError("active stable entry version does not match ToolReleaseBundle")
1759
+ if manifest["executable"]["kind"] == "source_files":
1760
+ sync_entry = next(
1761
+ (
1762
+ target
1763
+ for target, source in targets.items()
1764
+ if source.name == "tool-skill-sync"
1765
+ ),
1766
+ None,
1767
+ )
1768
+ if sync_entry is not None:
1769
+ result = run((str(sync_entry), "--version"))
1770
+ if result.returncode != 0 or extract_version(
1771
+ result.stdout + result.stderr
1772
+ ) != bundled_sync_version(bundle):
1773
+ raise SyncError("active tool-skill-sync smoke failed")
1774
+ return {
1775
+ "binary_version": binary["version"],
1776
+ "binary_sha256": binary["sha256"],
1777
+ "skill_sha256": release["skill_sha"],
1778
+ "cli_contract_sha256": release["cli_contract_sha"],
1779
+ "target_sha256": {
1780
+ str(target): sha256_file(target) for target in sorted(targets)
1781
+ },
1782
+ }
1783
+
1784
+
1785
+ def production_pair_matches(
1786
+ bundle: Path,
1787
+ *,
1788
+ agents_root: Path,
1789
+ bin_dir: Path | None,
1790
+ hooks_dir: Path,
1791
+ ) -> bool:
1792
+ targets, _ = production_target_sources(
1793
+ bundle,
1794
+ agents_root=agents_root,
1795
+ bin_dir=bin_dir,
1796
+ hooks_dir=hooks_dir,
1797
+ )
1798
+ for target, source in targets.items():
1799
+ if not target.exists() and not target.is_symlink():
1800
+ return False
1801
+ require_owned_regular(target, "active production target")
1802
+ if sha256_file(target) != sha256_file(source):
1803
+ return False
1804
+ verify_production_bundle(
1805
+ bundle,
1806
+ agents_root=agents_root,
1807
+ bin_dir=bin_dir,
1808
+ hooks_dir=hooks_dir,
1809
+ )
1810
+ return True
1811
+
1812
+
1813
+ def verify_production_backup(backup: Path) -> dict[str, Any]:
1814
+ require_owned_directory(backup)
1815
+ receipt = read_json(backup / "receipt.json")
1816
+ if set(receipt) != {"schema_version", "operation", "tool", "entries"} or (
1817
+ receipt.get("schema_version") != SCHEMA_VERSION
1818
+ or receipt.get("operation") != "production_pair_backup"
1819
+ or not isinstance(receipt.get("tool"), str)
1820
+ or not isinstance(receipt.get("entries"), list)
1821
+ ):
1822
+ raise SyncError("production backup receipt is invalid")
1823
+ seen: set[str] = set()
1824
+ for entry in receipt["entries"]:
1825
+ if not isinstance(entry, dict) or set(entry) != {
1826
+ "target",
1827
+ "backup_file",
1828
+ "sha256",
1829
+ "mode",
1830
+ }:
1831
+ raise SyncError("production backup entry is invalid")
1832
+ target = entry["target"]
1833
+ if (
1834
+ not isinstance(target, str)
1835
+ or not Path(target).is_absolute()
1836
+ or target in seen
1837
+ ):
1838
+ raise SyncError("production backup target is invalid or duplicated")
1839
+ seen.add(target)
1840
+ backup_file = entry["backup_file"]
1841
+ digest = entry["sha256"]
1842
+ mode = entry["mode"]
1843
+ if backup_file is None:
1844
+ if digest is not None or mode is not None:
1845
+ raise SyncError("absent production backup entry has file metadata")
1846
+ continue
1847
+ if (
1848
+ not isinstance(backup_file, str)
1849
+ or Path(backup_file).is_absolute()
1850
+ or ".." in Path(backup_file).parts
1851
+ or not isinstance(digest, str)
1852
+ or not HEX_SHA256.fullmatch(digest)
1853
+ or not isinstance(mode, int)
1854
+ ):
1855
+ raise SyncError("production backup file metadata is invalid")
1856
+ stored = backup / backup_file
1857
+ require_owned_regular(stored, "production backup file")
1858
+ if sha256_file(stored) != digest:
1859
+ raise SyncError("production backup file SHA mismatch")
1860
+ return receipt
1861
+
1862
+
1863
+ def capture_production_pair(
1864
+ tool: str,
1865
+ targets: Sequence[Path],
1866
+ production_root: Path,
1867
+ ) -> Path:
1868
+ backups_root = ensure_owned_subdirectory(production_root, Path("backups"))
1869
+ staging = Path(tempfile.mkdtemp(prefix=".staging-", dir=backups_root))
1870
+ staging.chmod(0o700)
1871
+ try:
1872
+ entries: list[dict[str, Any]] = []
1873
+ files_root = staging / "files"
1874
+ files_root.mkdir(mode=0o700)
1875
+ for index, target in enumerate(sorted(targets)):
1876
+ if not target.exists() and not target.is_symlink():
1877
+ entries.append(
1878
+ {
1879
+ "target": str(target),
1880
+ "backup_file": None,
1881
+ "sha256": None,
1882
+ "mode": None,
1883
+ }
1884
+ )
1885
+ continue
1886
+ require_owned_regular(target, "active production target")
1887
+ relative = f"files/{index:03d}"
1888
+ stored = staging / relative
1889
+ shutil.copyfile(target, stored)
1890
+ mode = stat.S_IMODE(target.stat().st_mode)
1891
+ stored.chmod(mode)
1892
+ entries.append(
1893
+ {
1894
+ "target": str(target),
1895
+ "backup_file": relative,
1896
+ "sha256": sha256_file(stored),
1897
+ "mode": mode,
1898
+ }
1899
+ )
1900
+ receipt = {
1901
+ "schema_version": SCHEMA_VERSION,
1902
+ "operation": "production_pair_backup",
1903
+ "tool": tool,
1904
+ "entries": entries,
1905
+ }
1906
+ write_json(staging / "receipt.json", receipt)
1907
+ identity = sha256_file(staging / "receipt.json")
1908
+ destination = backups_root / identity
1909
+ if destination.exists():
1910
+ verify_production_backup(destination)
1911
+ shutil.rmtree(staging)
1912
+ return destination
1913
+ os.replace(staging, destination)
1914
+ fsync_directory(backups_root)
1915
+ verify_production_backup(destination)
1916
+ return destination
1917
+ except BaseException:
1918
+ if staging.exists():
1919
+ shutil.rmtree(staging)
1920
+ raise
1921
+
1922
+
1923
+ def restore_production_pair(
1924
+ backup: Path, expected_targets: Sequence[Path], *, execution_locked: bool = False,
1925
+ ) -> None:
1926
+ if not execution_locked:
1927
+ with finalizer_execution_lock(expected_targets):
1928
+ return restore_production_pair(backup, expected_targets, execution_locked=True)
1929
+ receipt = verify_production_backup(backup)
1930
+ entries = {Path(entry["target"]): entry for entry in receipt["entries"]}
1931
+ if set(entries) != set(expected_targets):
1932
+ raise SyncError("production backup target set does not match active pair")
1933
+ staged: dict[Path, Path] = {}
1934
+ try:
1935
+ for target, entry in entries.items():
1936
+ if entry["backup_file"] is None:
1937
+ continue
1938
+ ensure_owned_subdirectory(target.parent, Path("."))
1939
+ descriptor, temporary_name = tempfile.mkstemp(
1940
+ dir=target.parent, prefix=f".{target.name}.restore-"
1941
+ )
1942
+ os.close(descriptor)
1943
+ temporary = Path(temporary_name)
1944
+ shutil.copyfile(backup / entry["backup_file"], temporary)
1945
+ temporary.chmod(entry["mode"])
1946
+ staged[target] = temporary
1947
+ for target, entry in entries.items():
1948
+ if entry["backup_file"] is None:
1949
+ if target.exists() or target.is_symlink():
1950
+ require_owned_regular(target, "active production target")
1951
+ target.unlink()
1952
+ fsync_directory(target.parent)
1953
+ continue
1954
+ os.replace(staged.pop(target), target)
1955
+ fsync_directory(target.parent)
1956
+ finally:
1957
+ for temporary in staged.values():
1958
+ if temporary.exists():
1959
+ temporary.unlink()
1960
+
1961
+
1962
+ def installed_skill_tree(agents_root: Path, bundle: Path) -> str | None:
1963
+ manifest = read_json(bundle / "tool_skill_manifest.json")
1964
+ installed_skill_name = (
1965
+ COMPATIBILITY_SKILL_NAME
1966
+ if manifest.get("schema_version") == 1
1967
+ else SKILL_NAME
1968
+ )
1969
+ skill_root = agents_root / "skills" / installed_skill_name
1970
+ present = [
1971
+ skill_root / relative
1972
+ for relative in SKILL_PAYLOAD
1973
+ if (skill_root / relative).exists() or (skill_root / relative).is_symlink()
1974
+ ]
1975
+ if not present:
1976
+ return None
1977
+ if len(present) != len(SKILL_PAYLOAD):
1978
+ missing = ", ".join(
1979
+ relative
1980
+ for relative in SKILL_PAYLOAD
1981
+ if not (skill_root / relative).exists()
1982
+ and not (skill_root / relative).is_symlink()
1983
+ )
1984
+ raise SyncError(
1985
+ "installed production Skill is incomplete; preserve and classify the "
1986
+ f"missing payload files before activation: {missing}"
1987
+ )
1988
+ return tree_sha256(skill_root, SKILL_PAYLOAD)
1989
+
1990
+
1991
+ def validate_production_skill_trusted(
1992
+ bundle: Path,
1993
+ agents_root: Path,
1994
+ *,
1995
+ previous_bundle: Path | None,
1996
+ ) -> None:
1997
+ live_tree = installed_skill_tree(agents_root, bundle)
1998
+ if live_tree is None:
1999
+ return
2000
+ bundle_tree = verify_bundle(bundle)["skill_sha"]
2001
+ if live_tree == bundle_tree:
2002
+ return
2003
+ if live_tree in RELEASED_CANONICAL_SKILL_SHA256:
2004
+ return
2005
+ if previous_bundle is not None and verify_bundle(previous_bundle)["skill_sha"] == live_tree:
2006
+ return
2007
+ manifest = read_json(bundle / "tool_skill_manifest.json")
2008
+ installed_skill_name = (
2009
+ COMPATIBILITY_SKILL_NAME
2010
+ if manifest.get("schema_version") == 1
2011
+ else SKILL_NAME
2012
+ )
2013
+ skill_root = agents_root / "skills" / installed_skill_name
2014
+ drifted = ", ".join(
2015
+ f"{relative} live={sha256_file(skill_root / relative)}"
2016
+ for relative in SKILL_PAYLOAD
2017
+ if sha256_file(skill_root / relative) != sha256_file(bundle / relative)
2018
+ )
2019
+ raise SyncError(
2020
+ f"unknown content drift in installed production Skill (live_tree={live_tree} "
2021
+ f"bundle_tree={bundle_tree} accepted_released_trees="
2022
+ f"{', '.join(sorted(RELEASED_CANONICAL_SKILL_SHA256))}); preserve and "
2023
+ "classify these files first, activation refuses to overwrite them: "
2024
+ + drifted
2025
+ )
2026
+
2027
+
2028
+ def replace_production_pair(targets: dict[Path, Path]) -> None:
2029
+ staged: dict[Path, Path] = {}
2030
+ try:
2031
+ for target, source in targets.items():
2032
+ require_owned_regular(source, "bundled production source")
2033
+ descriptor, temporary_name = tempfile.mkstemp(
2034
+ dir=target.parent, prefix=f".{target.name}.install-"
2035
+ )
2036
+ os.close(descriptor)
2037
+ temporary = Path(temporary_name)
2038
+ shutil.copyfile(source, temporary)
2039
+ temporary.chmod(stat.S_IMODE(source.stat().st_mode))
2040
+ staged[target] = temporary
2041
+ for target in sorted(staged):
2042
+ if target.exists() or target.is_symlink():
2043
+ require_owned_regular(target, "active production target")
2044
+ os.replace(staged.pop(target), target)
2045
+ fsync_directory(target.parent)
2046
+ finally:
2047
+ for temporary in staged.values():
2048
+ if temporary.exists():
2049
+ temporary.unlink()
2050
+
2051
+
2052
+ @contextmanager
2053
+ def finalizer_execution_lock(targets: Sequence[Path], *, timeout: float = DEFAULT_LOCK_TIMEOUT):
2054
+ """Keep active CLI readers out of a production activation or rollback."""
2055
+ entries = [target for target in targets if target.name == "git-finalize"]
2056
+ if not entries:
2057
+ yield
2058
+ return
2059
+ if len(entries) != 1:
2060
+ raise SyncError("ambiguous Finalizer execution lock target")
2061
+ lock_path = entries[0].with_name(".git-finalizer-execution.lock")
2062
+ require_owned_directory(lock_path.parent)
2063
+ descriptor = os.open(lock_path, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW | os.O_CLOEXEC, 0o600)
2064
+ try:
2065
+ info = os.fstat(descriptor)
2066
+ if not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid() or info.st_mode & 0o077:
2067
+ raise SyncError("unsafe Finalizer execution lock")
2068
+ _flock_exclusive_bounded(descriptor, timeout=timeout, label="Finalizer execution lock")
2069
+ yield
2070
+ finally:
2071
+ os.close(descriptor)
2072
+
2073
+
2074
+ def activate_production_bundle(
2075
+ bundle: Path,
2076
+ tool: str,
2077
+ production_root: Path,
2078
+ *,
2079
+ agents_root: Path,
2080
+ bin_dir: Path | None,
2081
+ hooks_dir: Path,
2082
+ previous_bundle: Path | None = None,
2083
+ ) -> tuple[Path | None, dict[str, Any]]:
2084
+ targets, live_bin_dir = production_target_sources(
2085
+ bundle,
2086
+ agents_root=agents_root,
2087
+ bin_dir=bin_dir,
2088
+ hooks_dir=hooks_dir,
2089
+ )
2090
+ validate_production_skill_trusted(
2091
+ bundle,
2092
+ agents_root,
2093
+ previous_bundle=previous_bundle,
2094
+ )
2095
+ previous_targets = {}
2096
+ if previous_bundle is not None:
2097
+ # Transition bookkeeping only: the retired target set is a static
2098
+ # property of the previous manifest. Installed-version consistency is
2099
+ # asserted against the incoming bundle and by the post-activation
2100
+ # verification, never against the superseded release.
2101
+ prev_manifest = read_json(previous_bundle / "tool_skill_manifest.json")
2102
+ cur_manifest = read_json(bundle / "tool_skill_manifest.json")
2103
+ prev_kind = prev_manifest["executable"]["kind"]
2104
+ cur_kind = cur_manifest["executable"]["kind"]
2105
+ prev_bin_dir = live_bin_dir
2106
+ new_entrypoints = validate_install_targets(cur_manifest, allow_legacy=True)
2107
+ if prev_bin_dir is None and prev_kind == "source_files":
2108
+ for name in new_entrypoints:
2109
+ found = shutil.which(name)
2110
+ if found:
2111
+ prev_bin_dir = Path(found).parent
2112
+ break
2113
+ previous_targets, resolved_prev_bin = production_target_sources(
2114
+ previous_bundle,
2115
+ agents_root=agents_root,
2116
+ bin_dir=prev_bin_dir,
2117
+ hooks_dir=hooks_dir,
2118
+ assert_installed_version=False,
2119
+ )
2120
+ if prev_kind == "source_files" and cur_kind == "python_console_scripts":
2121
+ # Keep active console scripts managed by uv tool install; only retire
2122
+ # genuinely obsolete source_files sidecars and helpers.
2123
+ new_entry_set = set(new_entrypoints)
2124
+ active_console_paths: set[Path] = set()
2125
+ for dir_cand in (resolved_prev_bin, bin_dir.resolve() if bin_dir else None):
2126
+ if dir_cand is not None:
2127
+ for name in new_entry_set:
2128
+ active_console_paths.add(dir_cand / name)
2129
+ try:
2130
+ uv_info = python_tool_installation(new_entrypoints, bin_dir)
2131
+ active_console_paths.update(
2132
+ Path(entry_path) for entry_path in uv_info["entry_targets"].values()
2133
+ )
2134
+ except SyncError:
2135
+ pass
2136
+ previous_targets = {
2137
+ target: source
2138
+ for target, source in previous_targets.items()
2139
+ if target not in active_console_paths
2140
+ and not (target.name in new_entry_set and target.is_symlink())
2141
+ }
2142
+ retired = set(previous_targets) - set(targets)
2143
+ for target in retired:
2144
+ if not target.exists() and not target.is_symlink():
2145
+ continue
2146
+ require_owned_regular(target, "retiring production target")
2147
+ source = previous_targets[target]
2148
+ if (sha256_file(target) != sha256_file(source)
2149
+ or stat.S_IMODE(target.stat().st_mode) != stat.S_IMODE(source.stat().st_mode)):
2150
+ raise SyncError(f"retiring production target drifted: {target}")
2151
+ all_targets = tuple(set(targets) | set(previous_targets))
2152
+ if not retired and production_pair_matches(
2153
+ bundle,
2154
+ agents_root=agents_root,
2155
+ bin_dir=live_bin_dir,
2156
+ hooks_dir=hooks_dir,
2157
+ ):
2158
+ return None, verify_production_bundle(
2159
+ bundle,
2160
+ agents_root=agents_root,
2161
+ bin_dir=live_bin_dir,
2162
+ hooks_dir=hooks_dir,
2163
+ )
2164
+ with finalizer_execution_lock(all_targets):
2165
+ backup = capture_production_pair(tool, all_targets, production_root)
2166
+ try:
2167
+ replace_production_pair(targets)
2168
+ verified = verify_production_bundle(
2169
+ bundle,
2170
+ agents_root=agents_root,
2171
+ bin_dir=live_bin_dir,
2172
+ hooks_dir=hooks_dir,
2173
+ )
2174
+ for target in retired:
2175
+ if target.exists():
2176
+ target.unlink()
2177
+ fsync_directory(target.parent)
2178
+ verified["retired_targets"] = sorted(map(str, retired))
2179
+ except BaseException:
2180
+ restore_production_pair(backup, all_targets, execution_locked=True)
2181
+ raise
2182
+ return backup, verified
2183
+
2184
+
2185
+ def resolve_production_backup(pointer: Path, backups_root: Path) -> Path | None:
2186
+ return resolve_pointer(pointer, backups_root)
2187
+
2188
+
2189
+ def restore_pointer(directory: Path, name: str, target: Path | None) -> None:
2190
+ pointer = directory / name
2191
+ if target is None:
2192
+ if pointer.exists() or pointer.is_symlink():
2193
+ if not pointer.is_symlink():
2194
+ raise SyncError(f"managed pointer is not a symlink: {pointer}")
2195
+ pointer.unlink()
2196
+ fsync_directory(directory)
2197
+ return
2198
+ atomic_symlink(directory, name, target)
2199
+
2200
+
2201
+ def build_bundle(
2202
+ sources: Sources,
2203
+ tool: str,
2204
+ bundles_root: Path,
2205
+ *,
2206
+ allow_dirty_source: bool,
2207
+ ) -> Path:
2208
+ checked = check_tool(sources, tool)
2209
+ if checked["status"] != "PASS":
2210
+ raise SyncError("canonical check failed: " + "; ".join(checked["errors"]))
2211
+ repo = sources.repo(tool)
2212
+ head = sources.head(tool)
2213
+ dirty = sources.dirty(tool) or git_dirty(sources.owner_repo)
2214
+ if dirty and not allow_dirty_source:
2215
+ raise SyncError(
2216
+ "source repositories are dirty; release bundle requires committed sources"
2217
+ )
2218
+ tool_commit = f"worktree:{head}" if dirty else head
2219
+ manifest = read_json(sources.manifest_path(tool))
2220
+ manifest["tool_commit"] = tool_commit
2221
+ tool_root = bundles_root / tool
2222
+ require_owned_directory(tool_root, create=True)
2223
+ staging = Path(tempfile.mkdtemp(prefix=".staging-", dir=tool_root))
2224
+ staging.chmod(0o700)
2225
+ try:
2226
+ copy_skill_payload(sources.skill_root, staging)
2227
+ copy_compatibility_skill(sources.compatibility_skill_root, staging)
2228
+ (staging / "tool_cli_contract.json").write_bytes(
2229
+ sources.source_bytes(tool, "tool_cli_contract.json")
2230
+ )
2231
+ (staging / "tool_cli_contract.json").chmod(0o600)
2232
+ write_json(staging / "tool_skill_manifest.json", manifest)
2233
+ executable_sha, _ = source_executable_payload(
2234
+ repo, manifest, staging, tool_commit
2235
+ )
2236
+ release = {
2237
+ "schema_version": SCHEMA_VERSION,
2238
+ "tool_name": tool,
2239
+ "tool_version": manifest["tool_version"],
2240
+ "tool_commit": tool_commit,
2241
+ "binary_or_entry_sha": executable_sha,
2242
+ "skill_sha": tree_sha256(staging, SKILL_PAYLOAD),
2243
+ "cli_contract_sha": sha256_file(staging / "tool_cli_contract.json"),
2244
+ "manifest_sha": sha256_file(staging / "tool_skill_manifest.json"),
2245
+ "source_state": "dirty_test_only" if dirty else "committed_release",
2246
+ }
2247
+ write_json(staging / "release_manifest.json", release)
2248
+ verify_bundle(staging, tool)
2249
+ smoke_bundle(staging)
2250
+ release_sha = sha256_file(staging / "release_manifest.json")
2251
+ safe_commit = tool_commit.replace(":", "-")[:21]
2252
+ bundle_name = f"{manifest['tool_version']}-{safe_commit}-{release_sha[:12]}"
2253
+ destination = tool_root / bundle_name
2254
+ if destination.exists():
2255
+ verify_bundle(destination, tool)
2256
+ shutil.rmtree(staging)
2257
+ return destination
2258
+ os.replace(staging, destination)
2259
+ return destination
2260
+ except BaseException:
2261
+ if staging.exists():
2262
+ shutil.rmtree(staging)
2263
+ raise
2264
+
2265
+
2266
+ def install(
2267
+ sources: Sources,
2268
+ tool: str,
2269
+ install_root: Path,
2270
+ *,
2271
+ allow_dirty_source: bool,
2272
+ activate_production: bool = False,
2273
+ agents_root: Path | None = None,
2274
+ bin_dir: Path | None = None,
2275
+ hooks_dir: Path | None = None,
2276
+ ) -> dict[str, Any]:
2277
+ roots = [install_root]
2278
+ if activate_production and agents_root is not None:
2279
+ roots.append(agents_root / "skills")
2280
+ with deployment_lock(*roots):
2281
+ return _install_unlocked(
2282
+ sources, tool, install_root, allow_dirty_source=allow_dirty_source,
2283
+ activate_production=activate_production, agents_root=agents_root,
2284
+ bin_dir=bin_dir, hooks_dir=hooks_dir,
2285
+ )
2286
+
2287
+
2288
+ def _install_unlocked(
2289
+ sources: Sources, tool: str, install_root: Path, *, allow_dirty_source: bool,
2290
+ activate_production: bool = False, agents_root: Path | None = None,
2291
+ bin_dir: Path | None = None, hooks_dir: Path | None = None,
2292
+ ) -> dict[str, Any]:
2293
+ require_owned_directory(install_root, create=True)
2294
+ bundles_root = install_root / "bundles"
2295
+ state_root = install_root / "tools" / tool
2296
+ require_owned_directory(bundles_root, create=True)
2297
+ require_owned_directory(state_root, create=True)
2298
+ bundle = build_bundle(
2299
+ sources,
2300
+ tool,
2301
+ bundles_root,
2302
+ allow_dirty_source=allow_dirty_source,
2303
+ )
2304
+ current = resolve_pointer(state_root / "CURRENT", bundles_root)
2305
+ if current == bundle and not activate_production:
2306
+ return {"status": "UNCHANGED", "tool": tool, "current_bundle": bundle.name}
2307
+ previous_before = resolve_pointer(state_root / "PREVIOUS", bundles_root)
2308
+ if current is not None:
2309
+ verify_bundle(current, tool)
2310
+ smoke_bundle(current)
2311
+
2312
+ production_root: Path | None = None
2313
+ production_previous: Path | None = None
2314
+ production_backup: Path | None = None
2315
+ production_verified: dict[str, Any] | None = None
2316
+ if activate_production:
2317
+ if agents_root is None or hooks_dir is None:
2318
+ raise SyncError("production activation requires agents_root and hooks_dir")
2319
+ production_root = state_root / "production"
2320
+ require_owned_directory(production_root, create=True)
2321
+ backups_root = ensure_owned_subdirectory(production_root, Path("backups"))
2322
+ production_previous = resolve_production_backup(
2323
+ production_root / "PREVIOUS", backups_root
2324
+ )
2325
+ production_backup, production_verified = activate_production_bundle(
2326
+ bundle,
2327
+ tool,
2328
+ production_root,
2329
+ agents_root=agents_root,
2330
+ bin_dir=bin_dir,
2331
+ hooks_dir=hooks_dir,
2332
+ previous_bundle=current,
2333
+ )
2334
+
2335
+ try:
2336
+ if current != bundle:
2337
+ if current is not None:
2338
+ atomic_symlink(state_root, "PREVIOUS", current)
2339
+ atomic_symlink(state_root, "CURRENT", bundle)
2340
+ active = resolve_pointer(state_root / "CURRENT", bundles_root)
2341
+ verify_bundle(active or bundle, tool)
2342
+ if production_backup is not None and production_root is not None:
2343
+ atomic_symlink(production_root, "PREVIOUS", production_backup)
2344
+ if activate_production:
2345
+ assert agents_root is not None
2346
+ assert hooks_dir is not None
2347
+ production_verified = verify_production_bundle(
2348
+ bundle,
2349
+ agents_root=agents_root,
2350
+ bin_dir=bin_dir,
2351
+ hooks_dir=hooks_dir,
2352
+ )
2353
+ except BaseException:
2354
+ if production_backup is not None:
2355
+ # Failure cleanup must never be blocked by pairing assertions;
2356
+ # these calls only rebuild the target set for byte-verified
2357
+ # restoration from the recorded backup.
2358
+ targets, _ = production_target_sources(
2359
+ bundle,
2360
+ agents_root=agents_root or Path(),
2361
+ bin_dir=bin_dir,
2362
+ hooks_dir=hooks_dir or Path(),
2363
+ assert_installed_version=False,
2364
+ )
2365
+ if current is not None:
2366
+ previous_targets, _ = production_target_sources(
2367
+ current, agents_root=agents_root or Path(), bin_dir=bin_dir,
2368
+ hooks_dir=hooks_dir or Path(),
2369
+ assert_installed_version=False,
2370
+ )
2371
+ targets.update(previous_targets)
2372
+ restore_production_pair(production_backup, tuple(targets))
2373
+ restore_pointer(state_root, "CURRENT", current)
2374
+ restore_pointer(state_root, "PREVIOUS", previous_before)
2375
+ if production_root is not None:
2376
+ restore_pointer(production_root, "PREVIOUS", production_previous)
2377
+ raise
2378
+ return {
2379
+ "status": "INSTALLED" if current != bundle else "ACTIVATED",
2380
+ "tool": tool,
2381
+ "current_bundle": bundle.name,
2382
+ "previous_bundle": current.name if current else None,
2383
+ "production_activation": activate_production,
2384
+ "production_verified": production_verified,
2385
+ }
2386
+
2387
+
2388
+ def rollback(
2389
+ tool: str,
2390
+ install_root: Path,
2391
+ *,
2392
+ activate_production: bool = False,
2393
+ agents_root: Path | None = None,
2394
+ bin_dir: Path | None = None,
2395
+ hooks_dir: Path | None = None,
2396
+ ) -> dict[str, Any]:
2397
+ roots = [install_root]
2398
+ if activate_production and agents_root is not None:
2399
+ roots.append(agents_root / "skills")
2400
+ with deployment_lock(*roots):
2401
+ return _rollback_unlocked(
2402
+ tool, install_root, activate_production=activate_production,
2403
+ agents_root=agents_root, bin_dir=bin_dir, hooks_dir=hooks_dir,
2404
+ )
2405
+
2406
+
2407
+ def _rollback_unlocked(
2408
+ tool: str, install_root: Path, *, activate_production: bool = False,
2409
+ agents_root: Path | None = None, bin_dir: Path | None = None,
2410
+ hooks_dir: Path | None = None,
2411
+ ) -> dict[str, Any]:
2412
+ bundles_root = install_root / "bundles"
2413
+ state_root = install_root / "tools" / tool
2414
+ require_owned_directory(bundles_root)
2415
+ require_owned_directory(state_root)
2416
+ current = resolve_pointer(state_root / "CURRENT", bundles_root)
2417
+ previous = resolve_pointer(state_root / "PREVIOUS", bundles_root)
2418
+ if current is None or previous is None:
2419
+ raise SyncError(f"rollback requires CURRENT and PREVIOUS for {tool}")
2420
+ verify_bundle(current, tool)
2421
+ verify_bundle(previous, tool)
2422
+ smoke_bundle(previous)
2423
+ production_root: Path | None = None
2424
+ production_previous: Path | None = None
2425
+ current_production_backup: Path | None = None
2426
+ production_verified: dict[str, Any] | None = None
2427
+ current_targets: dict[Path, Path] = {}
2428
+ if activate_production:
2429
+ if agents_root is None or hooks_dir is None:
2430
+ raise SyncError("production rollback requires agents_root and hooks_dir")
2431
+ production_root = state_root / "production"
2432
+ require_owned_directory(production_root)
2433
+ backups_root = ensure_owned_subdirectory(production_root, Path("backups"))
2434
+ production_previous = resolve_production_backup(
2435
+ production_root / "PREVIOUS", backups_root
2436
+ )
2437
+ current_targets, _ = production_target_sources(
2438
+ current,
2439
+ agents_root=agents_root,
2440
+ bin_dir=bin_dir,
2441
+ hooks_dir=hooks_dir,
2442
+ assert_installed_version=False,
2443
+ )
2444
+ previous_targets, _ = production_target_sources(
2445
+ previous,
2446
+ agents_root=agents_root,
2447
+ bin_dir=bin_dir,
2448
+ hooks_dir=hooks_dir,
2449
+ assert_installed_version=False,
2450
+ )
2451
+ retired = set(current_targets) - set(previous_targets)
2452
+ all_targets = tuple(set(current_targets) | set(previous_targets))
2453
+ if not any(p.exists() or p.is_symlink() for p in retired) and production_pair_matches(
2454
+ previous,
2455
+ agents_root=agents_root,
2456
+ bin_dir=bin_dir,
2457
+ hooks_dir=hooks_dir,
2458
+ ):
2459
+ production_verified = verify_production_bundle(
2460
+ previous,
2461
+ agents_root=agents_root,
2462
+ bin_dir=bin_dir,
2463
+ hooks_dir=hooks_dir,
2464
+ )
2465
+ else:
2466
+ if production_previous is None:
2467
+ raise SyncError(f"production rollback has no previous pair for {tool}")
2468
+ verify_production_bundle(
2469
+ current, agents_root=agents_root, bin_dir=bin_dir, hooks_dir=hooks_dir
2470
+ )
2471
+ receipt = verify_production_backup(production_previous)
2472
+ if {Path(entry["target"]) for entry in receipt["entries"]} != set(all_targets):
2473
+ raise SyncError("production rollback backup does not cover both target sets")
2474
+ current_production_backup = capture_production_pair(
2475
+ tool, all_targets, production_root
2476
+ )
2477
+ try:
2478
+ restore_production_pair(production_previous, all_targets)
2479
+ production_verified = verify_production_bundle(
2480
+ previous,
2481
+ agents_root=agents_root,
2482
+ bin_dir=bin_dir,
2483
+ hooks_dir=hooks_dir,
2484
+ )
2485
+ except BaseException:
2486
+ restore_production_pair(
2487
+ current_production_backup, all_targets
2488
+ )
2489
+ raise
2490
+ try:
2491
+ atomic_symlink(state_root, "PREVIOUS", current)
2492
+ atomic_symlink(state_root, "CURRENT", previous)
2493
+ active = resolve_pointer(state_root / "CURRENT", bundles_root)
2494
+ verify_bundle(active or previous, tool)
2495
+ if production_root is not None and current_production_backup is not None:
2496
+ atomic_symlink(production_root, "PREVIOUS", current_production_backup)
2497
+ except BaseException:
2498
+ restore_pointer(state_root, "CURRENT", current)
2499
+ restore_pointer(state_root, "PREVIOUS", previous)
2500
+ if current_production_backup is not None:
2501
+ restore_production_pair(current_production_backup, all_targets)
2502
+ if production_root is not None:
2503
+ restore_pointer(production_root, "PREVIOUS", production_previous)
2504
+ raise
2505
+ return {
2506
+ "status": "ROLLED_BACK",
2507
+ "tool": tool,
2508
+ "current_bundle": previous.name,
2509
+ "previous_bundle": current.name,
2510
+ "production_activation": activate_production,
2511
+ "production_verified": production_verified,
2512
+ }
2513
+
2514
+
2515
+ SKILL_LINK_CLIENTS = ("claude", "cursor", "qoder", "qoder-cn")
2516
+ MANAGED_SKILL_NAMES = (SKILL_NAME, COMPATIBILITY_SKILL_NAME)
2517
+
2518
+
2519
+ def _validate_skill_frontmatter_and_refs(skill_root: Path) -> None:
2520
+ skill_md = skill_root / "SKILL.md"
2521
+ require_regular(skill_md, "canonical SKILL.md")
2522
+ content = skill_md.read_text(encoding="utf-8")
2523
+ frontmatter = re.match(r"\A---\n(.*?)\n---\n", content, re.DOTALL)
2524
+ if frontmatter is None:
2525
+ raise SyncError("invalid YAML frontmatter delimiters in SKILL.md")
2526
+ lines = [line for line in frontmatter.group(1).splitlines() if line.strip()]
2527
+ fields = [line.split(":", 1)[0].strip() for line in lines if ":" in line]
2528
+ if fields != ["name", "description"]:
2529
+ raise SyncError("SKILL.md frontmatter must contain only name and description")
2530
+ name = next((line.split(":", 1)[1].strip() for line in lines if line.startswith("name:")), "")
2531
+ description = next((line.split(":", 1)[1].strip() for line in lines if line.startswith("description:")), "")
2532
+ if name != SKILL_NAME or not description or len(description) > 1024 or "<" in description or ">" in description:
2533
+ raise SyncError("SKILL.md frontmatter name or description is invalid")
2534
+ if len(content.splitlines()) >= 500 or any(line.endswith((" ", "\t")) for line in content.splitlines()):
2535
+ raise SyncError("SKILL.md exceeds line limit or contains trailing whitespace")
2536
+ for rel in SKILL_PAYLOAD:
2537
+ if rel.startswith("references/") and f"]({rel})" not in content:
2538
+ raise SyncError(f"SKILL.md does not link required reference: {rel}")
2539
+
2540
+
2541
+ def _validate_skill_source(sources: Sources) -> tuple[str, str]:
2542
+ require_owned_directory(sources.skill_root)
2543
+ for rel in SKILL_PAYLOAD:
2544
+ p = sources.skill_root / rel
2545
+ require_owned_regular(p, "canonical Skill payload")
2546
+ mode = stat.S_IMODE(p.stat().st_mode)
2547
+ if mode & 0o111 or mode & 0o002:
2548
+ raise SyncError(f"unsafe canonical Skill file permissions: {p} ({mode:#05o})")
2549
+ _validate_skill_frontmatter_and_refs(sources.skill_root)
2550
+ require_owned_directory(sources.compatibility_skill_root)
2551
+ compat_md = sources.compatibility_skill_root / "SKILL.md"
2552
+ require_owned_regular(compat_md, "compatibility Skill")
2553
+ compat_text = compat_md.read_text(encoding="utf-8")
2554
+ for marker in ("name: three-tool-git-workflow", "Deprecated compatibility entry", f"${SKILL_NAME}"):
2555
+ if marker not in compat_text:
2556
+ raise SyncError("compatibility Skill does not point to canonical Skill")
2557
+ return tree_sha256(sources.skill_root, SKILL_PAYLOAD), sha256_file(compat_md)
2558
+
2559
+
2560
+ def _default_client_homes(home_dir: Path | None = None) -> dict[str, Path]:
2561
+ base = home_dir or Path.home()
2562
+ return {
2563
+ "codex": Path(os.environ.get("CODEX_HOME", base / ".codex")),
2564
+ "claude": Path(os.environ.get("CLAUDE_CONFIG_DIR", base / ".claude")),
2565
+ "gemini": Path(os.environ.get("GEMINI_HOME", base / ".gemini")),
2566
+ "cursor": Path(os.environ.get("CURSOR_HOME", base / ".cursor")),
2567
+ "qoder": Path(os.environ.get("QODER_HOME", base / ".qoder")),
2568
+ "qoder-cn": Path(os.environ.get("QODER_CN_HOME", base / ".qoder-cn")),
2569
+ }
2570
+
2571
+
2572
+ def _check_multi_client_skills(
2573
+ agents_root: Path,
2574
+ client_homes: dict[str, Path],
2575
+ ) -> dict[str, Any]:
2576
+ shared_skills = agents_root / "skills"
2577
+ clients: dict[str, Any] = {}
2578
+ if (shared_skills / "synced").exists():
2579
+ raise SyncError("personal skill root contains disallowed account-synced directory: skills/synced")
2580
+
2581
+ # Codex reads ~/.agents/skills directly and adds no duplicate symlinks under ~/.codex/skills.
2582
+ codex_dir = client_homes["codex"]
2583
+ codex_dup = [
2584
+ name for name in MANAGED_SKILL_NAMES
2585
+ if (codex_dir / "skills" / name).exists() or (codex_dir / "skills" / name).is_symlink()
2586
+ ]
2587
+ clients["codex"] = {
2588
+ "present": codex_dir.is_dir(),
2589
+ "uses_shared_root": True,
2590
+ "duplicate_links": codex_dup,
2591
+ "status": "FAIL" if codex_dup else "PASS",
2592
+ }
2593
+
2594
+ for cname in SKILL_LINK_CLIENTS:
2595
+ cdir = client_homes[cname]
2596
+ if not cdir.is_dir():
2597
+ clients[cname] = {"present": False, "status": "SKIP"}
2598
+ continue
2599
+ cskills = cdir / "skills"
2600
+ if cskills.is_symlink() and cskills.resolve(strict=False) == shared_skills.resolve(strict=False):
2601
+ clients[cname] = {
2602
+ "present": True,
2603
+ "status": "FAIL",
2604
+ "error": f"{cname} uses a whole-root symlink to ~/.agents/skills instead of per-Skill links",
2605
+ }
2606
+ continue
2607
+ exposed: dict[str, bool] = {}
2608
+ for sname in MANAGED_SKILL_NAMES:
2609
+ link = cskills / sname
2610
+ target = shared_skills / sname
2611
+ exposed[sname] = link.exists() and link.resolve(strict=False) == target.resolve(strict=False)
2612
+ clients[cname] = {
2613
+ "present": True,
2614
+ "per_skill_links": exposed,
2615
+ "status": "PASS" if all(exposed.values()) else "DRIFT",
2616
+ }
2617
+
2618
+ gemini_dir = client_homes["gemini"]
2619
+ if not gemini_dir.is_dir():
2620
+ clients["gemini"] = {"present": False, "status": "SKIP"}
2621
+ else:
2622
+ cfg_path = gemini_dir / "config" / "skills.json"
2623
+ if not cfg_path.is_file():
2624
+ clients["gemini"] = {"present": True, "config": str(cfg_path), "status": "DRIFT"}
2625
+ else:
2626
+ try:
2627
+ cfg_data = json.loads(cfg_path.read_text(encoding="utf-8"))
2628
+ except (OSError, ValueError):
2629
+ clients["gemini"] = {"present": True, "config": str(cfg_path), "status": "FAIL"}
2630
+ else:
2631
+ expected_roots = {str(shared_skills), str(shared_skills / SKILL_NAME)}
2632
+ recorded: set[str] = set()
2633
+ if isinstance(cfg_data, dict):
2634
+ for key in ("paths", "skillPaths", "skills"):
2635
+ val = cfg_data.get(key)
2636
+ if isinstance(val, list):
2637
+ recorded.update(str(v) for v in val if isinstance(v, str))
2638
+ clients["gemini"] = {
2639
+ "present": True,
2640
+ "config": str(cfg_path),
2641
+ "registered_paths": sorted(recorded & expected_roots),
2642
+ "status": "PASS" if (recorded & expected_roots) else "DRIFT",
2643
+ }
2644
+ return clients
2645
+
2646
+
2647
+ def skill_check(
2648
+ sources: Sources,
2649
+ *,
2650
+ agents_root: Path,
2651
+ client_homes: dict[str, Path] | None = None,
2652
+ ) -> dict[str, Any]:
2653
+ canonical_sha, compat_sha = _validate_skill_source(sources)
2654
+ installed_sha, installed_compat_sha = installed_skill_hashes(agents_root)
2655
+ homes = _default_client_homes() if client_homes is None else client_homes
2656
+ clients = _check_multi_client_skills(agents_root, homes)
2657
+ trusted = (
2658
+ installed_sha in (None, canonical_sha)
2659
+ or installed_sha in RELEASED_CANONICAL_SKILL_SHA256
2660
+ )
2661
+ payload_match = installed_sha == canonical_sha and installed_compat_sha == compat_sha
2662
+ return {
2663
+ "schema_version": SCHEMA_VERSION,
2664
+ "operation": "skill-check",
2665
+ "status": "PASS" if (payload_match and trusted) else ("DRIFT" if trusted else "FAIL"),
2666
+ "source_skill_sha256": canonical_sha,
2667
+ "source_compatibility_sha256": compat_sha,
2668
+ "installed_skill_sha256": installed_sha,
2669
+ "installed_compatibility_sha256": installed_compat_sha,
2670
+ "trusted_lineage": trusted,
2671
+ "clients": clients,
2672
+ }
2673
+
2674
+
2675
+ def _sync_multi_client_skills(
2676
+ agents_root: Path,
2677
+ client_homes: dict[str, Path],
2678
+ ) -> dict[str, Any]:
2679
+ shared_skills = agents_root / "skills"
2680
+ require_owned_directory(shared_skills)
2681
+ if (shared_skills / "synced").exists():
2682
+ raise SyncError("refusing to sync while skills/synced exists inside shared personal root")
2683
+ results: dict[str, Any] = {}
2684
+
2685
+ for cname in SKILL_LINK_CLIENTS:
2686
+ cdir = client_homes[cname]
2687
+ if not cdir.is_dir():
2688
+ results[cname] = {"status": "SKIP"}
2689
+ continue
2690
+ cskills = cdir / "skills"
2691
+ if cskills.is_symlink():
2692
+ if cskills.resolve(strict=False) == shared_skills.resolve(strict=False):
2693
+ raise SyncError(f"{cname} skills directory must not symlink whole shared root")
2694
+ raise SyncError(f"{cname} skills directory is an unsafe symlink: {cskills}")
2695
+ require_owned_directory(cskills, create=True)
2696
+ linked: list[str] = []
2697
+ for sname in MANAGED_SKILL_NAMES:
2698
+ link_path = cskills / sname
2699
+ target = shared_skills / sname
2700
+ if link_path.is_symlink():
2701
+ if link_path.resolve(strict=False) == target.resolve(strict=False):
2702
+ linked.append(sname)
2703
+ continue
2704
+ link_path.unlink()
2705
+ elif link_path.exists():
2706
+ raise SyncError(f"{cname} already has non-symlink skill at {link_path}; preserve manually")
2707
+ os.symlink(str(target), link_path)
2708
+ linked.append(sname)
2709
+ results[cname] = {"status": "SYNCED", "linked": linked}
2710
+
2711
+ gemini_dir = client_homes["gemini"]
2712
+ if not gemini_dir.is_dir():
2713
+ results["gemini"] = {"status": "SKIP"}
2714
+ else:
2715
+ cfg_dir = ensure_owned_subdirectory(gemini_dir, Path("config"))
2716
+ cfg_path = cfg_dir / "skills.json"
2717
+ if cfg_path.is_symlink():
2718
+ raise SyncError(f"unsafe Gemini config symlink: {cfg_path}")
2719
+ if cfg_path.exists():
2720
+ try:
2721
+ cfg = json.loads(cfg_path.read_text(encoding="utf-8"))
2722
+ except (OSError, ValueError) as exc:
2723
+ raise SyncError(f"invalid existing Gemini skills.json: {exc}") from exc
2724
+ if not isinstance(cfg, dict):
2725
+ raise SyncError("Gemini skills.json root must be an object")
2726
+ else:
2727
+ cfg = {}
2728
+ key = "paths" if "paths" in cfg or "skillPaths" not in cfg else "skillPaths"
2729
+ existing = cfg.get(key)
2730
+ if existing is None:
2731
+ entries: list[str] = []
2732
+ elif isinstance(existing, list) and all(isinstance(x, str) for x in existing):
2733
+ entries = list(existing)
2734
+ else:
2735
+ raise SyncError(f"Gemini skills.json field {key} must be a list of strings")
2736
+ shared_str = str(shared_skills)
2737
+ if shared_str not in entries:
2738
+ entries.append(shared_str)
2739
+ cfg[key] = entries
2740
+ write_json(cfg_path, cfg, mode=0o600)
2741
+ results["gemini"] = {"status": "SYNCED", "config": str(cfg_path), "registered": shared_str}
2742
+
2743
+ codex_dir = client_homes["codex"]
2744
+ results["codex"] = {"status": "NATIVE", "shared_root": str(shared_skills), "present": codex_dir.is_dir()}
2745
+ return results
2746
+
2747
+
2748
+ def skill_install(
2749
+ sources: Sources,
2750
+ *,
2751
+ agents_root: Path,
2752
+ client_homes: dict[str, Path] | None = None,
2753
+ sync_clients: bool = True,
2754
+ ) -> dict[str, Any]:
2755
+ canonical_sha, compat_sha = _validate_skill_source(sources)
2756
+ require_owned_directory(agents_root, create=True)
2757
+ skills_root = ensure_owned_subdirectory(agents_root, Path("skills"))
2758
+ if (skills_root / "synced").exists():
2759
+ raise SyncError("refusing installation while skills/synced exists inside shared root")
2760
+ with deployment_lock(skills_root):
2761
+ live_canonical = skills_root / SKILL_NAME
2762
+ if live_canonical.exists():
2763
+ if live_canonical.is_symlink():
2764
+ raise SyncError(f"live Skill target is a symlink: {live_canonical}")
2765
+ installed_sha, _ = installed_skill_hashes(agents_root)
2766
+ if installed_sha not in (canonical_sha, None) and installed_sha not in RELEASED_CANONICAL_SKILL_SHA256:
2767
+ raise SyncError("unknown content drift in live Skill; preserve before installing")
2768
+
2769
+ stage_root = Path(tempfile.mkdtemp(prefix=".skill-stage-", dir=skills_root))
2770
+ try:
2771
+ copy_skill_payload(sources.skill_root, stage_root / SKILL_NAME)
2772
+ copy_compatibility_skill(sources.compatibility_skill_root, stage_root)
2773
+ canon_target = ensure_owned_subdirectory(skills_root, Path(SKILL_NAME))
2774
+ for rel in SKILL_PAYLOAD:
2775
+ dest = canon_target / rel
2776
+ ensure_owned_subdirectory(canon_target, Path(rel).parent)
2777
+ if dest.is_symlink():
2778
+ raise SyncError(f"live target file is a symlink: {dest}")
2779
+ shutil.copyfile(sources.skill_root / rel, dest)
2780
+ dest.chmod(0o600)
2781
+ compat_dir = ensure_owned_subdirectory(skills_root, Path(COMPATIBILITY_SKILL_NAME))
2782
+ compat_dest = compat_dir / "SKILL.md"
2783
+ if compat_dest.is_symlink():
2784
+ raise SyncError(f"live compatibility target is a symlink: {compat_dest}")
2785
+ shutil.copyfile(sources.compatibility_skill_root / "SKILL.md", compat_dest)
2786
+ compat_dest.chmod(0o600)
2787
+ finally:
2788
+ if stage_root.exists():
2789
+ shutil.rmtree(stage_root)
2790
+
2791
+ homes = _default_client_homes() if client_homes is None else client_homes
2792
+ clients = _sync_multi_client_skills(agents_root, homes) if sync_clients else {}
2793
+
2794
+ installed_sha, installed_compat_sha = installed_skill_hashes(agents_root)
2795
+ if installed_sha != canonical_sha or installed_compat_sha != compat_sha:
2796
+ raise SyncError("post-install Skill payload hash verification failed")
2797
+ return {
2798
+ "schema_version": SCHEMA_VERSION,
2799
+ "operation": "skill-install",
2800
+ "status": "INSTALLED",
2801
+ "skill_sha256": installed_sha,
2802
+ "compatibility_skill_sha256": installed_compat_sha,
2803
+ "clients": clients,
2804
+ }
2805
+
2806
+
2807
+ def _default_source_root(repo: Path | None = None) -> Path:
2808
+ env_root = os.environ.get("TOOL_SKILL_SYNC_SOURCE_ROOT", "").strip()
2809
+ if env_root:
2810
+ return Path(env_root).expanduser()
2811
+ resolved_file = Path(__file__).resolve()
2812
+ if len(resolved_file.parents) > 3:
2813
+ checkout_root = resolved_file.parents[3]
2814
+ if (checkout_root / "toolchain_compatibility.json").is_file():
2815
+ return checkout_root.parent
2816
+ if repo is not None:
2817
+ candidate = repo.resolve(strict=False)
2818
+ for parent in (candidate, *candidate.parents):
2819
+ if (parent / "toolchain_compatibility.json").is_file():
2820
+ return parent.parent
2821
+ projects_root = Path.home() / "projects"
2822
+ if (projects_root / "git-finalizer" / "toolchain_compatibility.json").is_file():
2823
+ return projects_root
2824
+ cwd = Path.cwd().resolve(strict=False)
2825
+ for parent in (cwd, *cwd.parents):
2826
+ if (parent / "toolchain_compatibility.json").is_file():
2827
+ return parent.parent
2828
+ return projects_root
2829
+
2830
+
2831
+ def parser() -> argparse.ArgumentParser:
2832
+ result = argparse.ArgumentParser(prog="tool-skill-sync")
2833
+ result.add_argument("--version", action="version", version=f"%(prog)s {VERSION}")
2834
+ result.add_argument("--source-root", type=Path, default=_default_source_root())
2835
+ result.add_argument(
2836
+ "--source-repo", action="append", default=[], metavar="TOOL=PATH",
2837
+ help="explicit source checkout; repeat for independently allocated worktrees",
2838
+ )
2839
+ result.add_argument(
2840
+ "--install-root",
2841
+ type=Path,
2842
+ default=Path.home() / ".local" / "state" / "tool-skill-sync",
2843
+ )
2844
+ result.add_argument(
2845
+ "--source-ref", action="append", default=[], metavar="TOOL=FULL_COMMIT_OID",
2846
+ help="read released Python package metadata from an exact commit without touching its checkout",
2847
+ )
2848
+ result.add_argument("--agents-root", type=Path, default=Path.home() / ".agents")
2849
+ result.add_argument("--bin-dir", type=Path)
2850
+ result.add_argument(
2851
+ "--hooks-dir", type=Path, default=Path.home() / ".agents" / "hooks"
2852
+ )
2853
+ subcommands = result.add_subparsers(dest="command", required=True)
2854
+ subcommands.add_parser("status")
2855
+ for sname in ("skill-check", "skill-install"):
2856
+ sp = subcommands.add_parser(sname)
2857
+ sp.add_argument("--codex-home", type=Path)
2858
+ sp.add_argument("--claude-home", type=Path)
2859
+ sp.add_argument("--gemini-home", type=Path)
2860
+ sp.add_argument("--cursor-home", type=Path)
2861
+ sp.add_argument("--qoder-home", type=Path)
2862
+ if sname == "skill-install":
2863
+ sp.add_argument("--no-sync-clients", action="store_true")
2864
+ doctor_parser = subcommands.add_parser(
2865
+ "doctor", help="read-only toolchain deployment and instruction freshness check"
2866
+ )
2867
+ doctor_parser.add_argument("--repo", type=Path)
2868
+ doctor_parser.add_argument("--summary", action="store_true")
2869
+ doctor_parser.add_argument("--previous-fingerprint")
2870
+ doctor_parser.add_argument(
2871
+ "--codex-home",
2872
+ type=Path,
2873
+ default=Path(os.environ.get("CODEX_HOME", Path.home() / ".codex")),
2874
+ )
2875
+ doctor_parser.add_argument(
2876
+ "--claude-home",
2877
+ type=Path,
2878
+ default=Path(os.environ.get("CLAUDE_CONFIG_DIR", Path.home() / ".claude")),
2879
+ )
2880
+ doctor_parser.add_argument("--controller", type=Path)
2881
+ doctor_parser.add_argument("--controller-source", type=Path)
2882
+ doctor_parser.add_argument(
2883
+ "--controller-runtime-root",
2884
+ type=Path,
2885
+ default=Path.home() / ".local/share/worktree-controller",
2886
+ )
2887
+ check_parser = subcommands.add_parser("check")
2888
+ check_parser.add_argument("tool")
2889
+ check_parser.add_argument(
2890
+ "--source-only",
2891
+ action="store_true",
2892
+ help=(
2893
+ "validate only the canonical source contract and skip installed-production "
2894
+ "drift detection (for build environments with no installation)"
2895
+ ),
2896
+ )
2897
+ install_parser = subcommands.add_parser("install")
2898
+ install_parser.add_argument("tool")
2899
+ install_parser.add_argument("--allow-dirty-source", action="store_true")
2900
+ install_parser.add_argument("--activate-production", action="store_true")
2901
+ upgrade_parser = subcommands.add_parser("upgrade")
2902
+ upgrade_parser.add_argument("tool")
2903
+ upgrade_parser.add_argument("--dry-run", action="store_true")
2904
+ upgrade_parser.add_argument(
2905
+ "--previous-bundle",
2906
+ type=Path,
2907
+ help="verified prior release identity when all console-script names changed",
2908
+ )
2909
+ rollback_parser = subcommands.add_parser("rollback")
2910
+ rollback_parser.add_argument("tool")
2911
+ rollback_parser.add_argument("--activate-production", action="store_true")
2912
+ return result
2913
+
2914
+
2915
+ def main(arguments: Sequence[str] | None = None) -> int:
2916
+ raw_argv = list(sys.argv[1:] if arguments is None else arguments)
2917
+ args = parser().parse_args(raw_argv)
2918
+ explicit_source_root = any(
2919
+ tok == "--source-root" or tok.startswith("--source-root=") for tok in raw_argv
2920
+ )
2921
+ source_root = args.source_root
2922
+ if (
2923
+ not explicit_source_root
2924
+ and getattr(args, "repo", None) is not None
2925
+ and not (source_root / "git-finalizer" / "toolchain_compatibility.json").is_file()
2926
+ ):
2927
+ source_root = _default_source_root(repo=args.repo)
2928
+ try:
2929
+ source_repos = {}
2930
+ for value in args.source_repo:
2931
+ name, separator, path = value.partition("=")
2932
+ if not separator or not SAFE_NAME.fullmatch(name) or not Path(path).is_absolute():
2933
+ raise SyncError("source-repo requires TOOL=/absolute/path")
2934
+ if name in source_repos:
2935
+ raise SyncError("source-repo contains a duplicate tool")
2936
+ source_repos[name] = Path(path)
2937
+ source_refs = {}
2938
+ for value in args.source_ref:
2939
+ name, separator, oid = value.partition("=")
2940
+ if not separator or not SAFE_NAME.fullmatch(name) or not FULL_GIT_OID.fullmatch(oid):
2941
+ raise SyncError("source-ref requires TOOL=FULL_COMMIT_OID")
2942
+ if name in source_refs:
2943
+ raise SyncError("source-ref contains a duplicate tool")
2944
+ source_refs[name] = oid
2945
+ sources = Sources(source_root, source_repos, source_refs)
2946
+ if args.command in {"skill-check", "skill-install"}:
2947
+ homes = _default_client_homes()
2948
+ for key, attr in (
2949
+ ("codex", "codex_home"),
2950
+ ("claude", "claude_home"),
2951
+ ("gemini", "gemini_home"),
2952
+ ("cursor", "cursor_home"),
2953
+ ("qoder", "qoder_home"),
2954
+ ):
2955
+ val = getattr(args, attr, None)
2956
+ if val is not None:
2957
+ homes[key] = val.resolve()
2958
+ if args.command == "skill-check":
2959
+ output = skill_check(sources, agents_root=args.agents_root.resolve(), client_homes=homes)
2960
+ print(canonical_json(output).decode(), end="")
2961
+ return 0 if output["status"] == "PASS" else 1
2962
+ output = skill_install(
2963
+ sources,
2964
+ agents_root=args.agents_root.resolve(),
2965
+ client_homes=homes,
2966
+ sync_clients=not args.no_sync_clients,
2967
+ )
2968
+ print(canonical_json(output).decode(), end="")
2969
+ return 0
2970
+ if args.command == "doctor":
2971
+ from . import workflow_health
2972
+ output = workflow_health.doctor(
2973
+ sources,
2974
+ agents_root=args.agents_root.resolve(),
2975
+ bin_dir=args.bin_dir,
2976
+ hooks_dir=args.hooks_dir.resolve(),
2977
+ repo=args.repo,
2978
+ codex_home=args.codex_home.resolve(),
2979
+ controller=args.controller,
2980
+ claude_home=args.claude_home.resolve(),
2981
+ controller_runtime_root=args.controller_runtime_root,
2982
+ controller_source=args.controller_source or source_root / "worktree-controller",
2983
+ previous_fingerprint=args.previous_fingerprint,
2984
+ )
2985
+ print(canonical_json(workflow_health.summary(output) if args.summary else output).decode(), end="")
2986
+ return 0 if output["status"] == "PASS" else 1
2987
+ if args.command == "status":
2988
+ output = status(sources, args.agents_root.resolve(), args.bin_dir)
2989
+ else:
2990
+ if args.tool not in sources.names():
2991
+ raise SyncError(f"unknown tool: {args.tool}")
2992
+ if args.command == "check":
2993
+ output = (
2994
+ check_tool(sources, args.tool)
2995
+ if args.source_only
2996
+ else check_tool_deployment(
2997
+ sources,
2998
+ args.tool,
2999
+ args.agents_root.resolve(),
3000
+ args.bin_dir,
3001
+ args.hooks_dir.resolve(),
3002
+ )
3003
+ )
3004
+ print(canonical_json(output).decode(), end="")
3005
+ return 0 if output["status"] == "PASS" else 1
3006
+ if args.command == "upgrade":
3007
+ output = upgrade(
3008
+ sources,
3009
+ args.tool,
3010
+ bin_dir=args.bin_dir,
3011
+ dry_run=args.dry_run,
3012
+ previous_bundle=args.previous_bundle,
3013
+ )
3014
+ print(canonical_json(output).decode(), end="")
3015
+ return 0
3016
+ if args.command == "install":
3017
+ output = install(
3018
+ sources,
3019
+ args.tool,
3020
+ args.install_root.resolve(),
3021
+ allow_dirty_source=args.allow_dirty_source,
3022
+ activate_production=args.activate_production,
3023
+ agents_root=args.agents_root.resolve(),
3024
+ bin_dir=args.bin_dir.resolve() if args.bin_dir else None,
3025
+ hooks_dir=args.hooks_dir.resolve(),
3026
+ )
3027
+ else:
3028
+ output = rollback(
3029
+ args.tool,
3030
+ args.install_root.resolve(),
3031
+ activate_production=args.activate_production,
3032
+ agents_root=args.agents_root.resolve(),
3033
+ bin_dir=args.bin_dir.resolve() if args.bin_dir else None,
3034
+ hooks_dir=args.hooks_dir.resolve(),
3035
+ )
3036
+ print(canonical_json(output).decode(), end="")
3037
+ return 0
3038
+ except (OSError, SyncError, subprocess.SubprocessError) as exc:
3039
+ print(f"tool-skill-sync: {exc}", file=sys.stderr)
3040
+ return 2
3041
+
3042
+
3043
+ if __name__ == "__main__":
3044
+ raise SystemExit(main())