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,504 @@
1
+ """Read-only deployed workflow and instruction diagnostics; never activates a tool."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import os
8
+ from pathlib import Path
9
+ import shutil
10
+ import subprocess
11
+ import tomllib
12
+ from typing import Any
13
+
14
+ # GF-INTEGRATION-ADAPTER: workflow-deployment-health (single site; read-only installed runtime probes)
15
+ try:
16
+ from . import tool_skill_sync as sync
17
+ except ImportError:
18
+ import tool_skill_sync as sync
19
+
20
+
21
+ def readonly_git(repo: Path, *arguments: str) -> str:
22
+ result = sync.run(
23
+ ["git", "-c", "core.fsmonitor=false", "-C", str(repo), *arguments],
24
+ env=dict(os.environ, GIT_OPTIONAL_LOCKS="0", GIT_NO_REPLACE_OBJECTS="1"),
25
+ )
26
+ if result.returncode:
27
+ raise sync.SyncError(f"read-only Git observation failed: {repo}")
28
+ return result.stdout.strip()
29
+
30
+
31
+ def fingerprint(value: Any) -> str:
32
+ return hashlib.sha256(sync.canonical_json(value)).hexdigest()
33
+
34
+
35
+ def file_identity(path: Path) -> dict[str, Any]:
36
+ resolved = path.resolve(strict=True)
37
+ if not resolved.is_file():
38
+ raise sync.SyncError(f"instruction is not a regular file: {path}")
39
+ content = resolved.read_bytes()
40
+ content.decode("utf-8")
41
+ return {
42
+ "path": str(path),
43
+ "real_path": str(resolved),
44
+ "sha256": hashlib.sha256(content).hexdigest(),
45
+ "bytes": len(content),
46
+ }
47
+
48
+
49
+ def installed_tool(
50
+ sources: sync.Sources,
51
+ tool: str,
52
+ agents_root: Path,
53
+ bin_dir: Path | None,
54
+ hooks_dir: Path,
55
+ ) -> dict[str, Any]:
56
+ return sync.check_tool_deployment(sources, tool, agents_root, bin_dir, hooks_dir)
57
+
58
+
59
+ def controller_commit(runtime: Path) -> str:
60
+ label = runtime.parent.name
61
+ if sync.FULL_GIT_OID.fullmatch(label):
62
+ return label
63
+ origins = list(runtime.glob("lib/python*/site-packages/worktree_controller-*.dist-info/direct_url.json"))
64
+ if (
65
+ not 7 <= len(label) < 40
66
+ or any(char not in "0123456789abcdef" for char in label)
67
+ or len(origins) != 1
68
+ ):
69
+ raise sync.SyncError("active runtime does not identify a full pinned commit")
70
+ origin = json.loads(origins[0].read_text(encoding="utf-8"))
71
+ vcs = origin.get("vcs_info") if isinstance(origin, dict) else None
72
+ commit = vcs.get("commit_id") if isinstance(vcs, dict) else None
73
+ if (
74
+ not isinstance(commit, str)
75
+ or not sync.FULL_GIT_OID.fullmatch(commit)
76
+ or not commit.startswith(label)
77
+ or vcs.get("vcs") != "git"
78
+ or vcs.get("requested_revision") not in (label, commit)
79
+ ):
80
+ raise sync.SyncError("active runtime does not identify a full pinned commit")
81
+ return commit
82
+
83
+
84
+ def controller_source(runtime: Path, commit: str, legacy: Path) -> tuple[Path, dict[str, Any] | None]:
85
+ """Consume the installer's public source locator; absence keeps the legacy source."""
86
+ manifest = runtime / "controller-source.json"
87
+ if not manifest.exists() and not manifest.is_symlink():
88
+ return legacy, None
89
+ sync.require_owned_regular(manifest, "Controller runtime source manifest")
90
+ if manifest.stat().st_mode & 0o022 or manifest.stat().st_size > 65536:
91
+ raise sync.SyncError("Controller runtime source manifest is writable by others or oversized")
92
+ value = sync.read_json(manifest)
93
+ expected = {
94
+ "schema_version",
95
+ "contract",
96
+ "commit",
97
+ "source_repository",
98
+ "git_common_dir",
99
+ "root_commit",
100
+ "contract_sha256",
101
+ "skill_sha256",
102
+ }
103
+ if (
104
+ set(value) != expected
105
+ or type(value.get("schema_version")) is not int
106
+ or value["schema_version"] != 1
107
+ or value.get("contract") != "controller-runtime-source/v1"
108
+ or value.get("commit") != commit
109
+ or not isinstance(value.get("root_commit"), str)
110
+ or not sync.FULL_GIT_OID.fullmatch(value["root_commit"])
111
+ ):
112
+ raise sync.SyncError("Controller runtime source manifest identity is invalid")
113
+ locations = []
114
+ for key in ("source_repository", "git_common_dir"):
115
+ raw = value.get(key)
116
+ if not isinstance(raw, str) or not Path(raw).is_absolute():
117
+ raise sync.SyncError("Controller source locator must be an absolute path")
118
+ path = Path(raw)
119
+ if path.resolve(strict=True) != path:
120
+ raise sync.SyncError("Controller source locator must be canonical")
121
+ sync.require_owned_directory(path)
122
+ locations.append(path)
123
+ repository, common = locations
124
+ if (
125
+ Path(readonly_git(repository, "rev-parse", "--show-toplevel")).resolve() != repository
126
+ or Path(readonly_git(repository, "rev-parse", "--path-format=absolute", "--git-common-dir")).resolve() != common
127
+ or readonly_git(repository, "rev-list", "--max-parents=0", commit).splitlines() != [value["root_commit"]]
128
+ ):
129
+ raise sync.SyncError("Controller source repository identity changed")
130
+ return repository, {
131
+ **file_identity(manifest),
132
+ "contract_sha256": value["contract_sha256"],
133
+ "skill_sha256": value["skill_sha256"],
134
+ }
135
+
136
+
137
+ def controller_state(
138
+ requirements: dict[str, Any],
139
+ entrypoint: Path | None,
140
+ runtime_root: Path,
141
+ source_repo: Path,
142
+ agents_root: Path,
143
+ ) -> dict[str, Any]:
144
+ result: dict[str, Any] = {
145
+ "tool": "worktree-controller",
146
+ "status": "FAIL",
147
+ "errors": [],
148
+ "source_repo": str(source_repo),
149
+ "source_is_candidate": True,
150
+ }
151
+ try:
152
+ sync.validate_controller_requirements(requirements)
153
+ entry = entrypoint or (Path(shutil.which("worktree-controller")) if shutil.which("worktree-controller") else None)
154
+ if entry is None:
155
+ raise sync.SyncError("worktree-controller is not installed")
156
+ active = runtime_root / "active"
157
+ runtime = active.resolve(strict=True)
158
+ environment = dict(
159
+ os.environ,
160
+ PYTHONDONTWRITEBYTECODE="1",
161
+ GIT_OPTIONAL_LOCKS="0",
162
+ GIT_NO_REPLACE_OBJECTS="1",
163
+ )
164
+ command = sync.run([str(entry), "capabilities", "--json"], env=environment)
165
+ if command.returncode != 0:
166
+ raise sync.SyncError("installed Controller capabilities probe failed")
167
+ envelope = json.loads(command.stdout)
168
+ if not isinstance(envelope, dict) or envelope.get("errors") or not isinstance(envelope.get("decision"), dict):
169
+ raise sync.SyncError("Controller returned invalid capability evidence")
170
+ caps = envelope["decision"]
171
+ result.update(
172
+ entrypoint=str(entry),
173
+ software_version=envelope.get("tool_version"),
174
+ cli_contract_version=caps.get("contract_version"),
175
+ capabilities_version=caps.get("capabilities_version"),
176
+ storage_layout_version=caps.get("storage_layout_version"),
177
+ )
178
+ for key, allowed_key in [
179
+ ("contract_version", "cli_contract_versions"),
180
+ ("storage_layout_version", "storage_layout_versions"),
181
+ ]:
182
+ if type(caps.get(key)) is not int or caps.get(key) not in requirements[allowed_key]:
183
+ result["errors"].append(f"unreviewed {key}: {caps.get(key)}")
184
+ # Backward-compatible capability minimum: accept observed >= expected.
185
+ for name, expected in requirements.get("capability_versions", {}).items():
186
+ if type(caps.get(name)) is not int or caps.get(name) < expected:
187
+ result["errors"].append(f"{name}: expected >= {expected}, observed {caps.get(name)}")
188
+ result["capability_versions"] = {
189
+ name: caps.get(name) for name in requirements.get("capability_versions", {})
190
+ }
191
+ result["active_runtime"] = str(runtime)
192
+ contracts = list(runtime.glob("lib/python*/site-packages/worktree_controller/tool_cli_contract.json"))
193
+ if len(contracts) != 1:
194
+ raise sync.SyncError("active Controller frozen contract is missing/ambiguous")
195
+ contract = json.loads(contracts[0].read_text(encoding="utf-8"))
196
+ for name in dict.fromkeys((
197
+ "contract_version",
198
+ "capabilities_version",
199
+ "storage_layout_version",
200
+ *requirements.get("capability_versions", {}),
201
+ )):
202
+ if caps.get(name) != contract.get(name):
203
+ result["errors"].append(f"runtime/frozen contract disagree: {name}")
204
+ if envelope.get("tool_version") != contract.get("tool_version"):
205
+ result["errors"].append("software version differs from frozen runtime contract")
206
+ result["frozen_contract_sha256"] = sync.sha256_file(contracts[0])
207
+ result["artifact_verification"] = sync.verify_installed_record(runtime)
208
+ # The active pinned commit is independent of the currently edited source checkout.
209
+ commit = controller_commit(runtime)
210
+ result["active_commit"] = commit
211
+ source_repo, source_manifest = controller_source(runtime, commit, source_repo)
212
+ result["source_repo"] = str(source_repo)
213
+ result["source_selection"] = "runtime-source-manifest" if source_manifest else "legacy-source-root"
214
+ if source_manifest:
215
+ result["source_manifest"] = source_manifest
216
+ if source_manifest["contract_sha256"] != result["frozen_contract_sha256"]:
217
+ result["errors"].append("runtime source manifest contract hash differs from installed contract")
218
+ observed = sync.run(["git", "-C", str(source_repo), "show", f"{commit}:tool_cli_contract.json"], env=environment)
219
+ if observed.returncode != 0 or hashlib.sha256(observed.stdout.encode()).hexdigest() != result["frozen_contract_sha256"]:
220
+ result["errors"].append("frozen contract does not match active commit")
221
+ result["source_head"] = sync.git_head(source_repo)
222
+ result["source_dirty"] = sync.git_dirty(source_repo)
223
+ skill = agents_root / "skills/worktree-lifecycle/SKILL.md"
224
+ result["installed_skill"] = file_identity(skill)
225
+ if source_manifest and source_manifest["skill_sha256"] != result["installed_skill"]["sha256"]:
226
+ result["errors"].append("runtime source manifest Skill hash differs from installed Skill")
227
+ published_skill = sync.run(
228
+ ["git", "-C", str(source_repo), "show", f"{commit}:skills/worktree-lifecycle/SKILL.md"],
229
+ env=environment,
230
+ )
231
+ if (
232
+ published_skill.returncode != 0
233
+ or hashlib.sha256(published_skill.stdout.encode()).hexdigest() != result["installed_skill"]["sha256"]
234
+ ):
235
+ result["errors"].append("installed worktree-lifecycle Skill differs from active commit; coordinate with WC owner")
236
+ if active.resolve(strict=True) != runtime:
237
+ result["errors"].append("Controller active runtime changed during observation; retry read-only check")
238
+ if source_manifest:
239
+ manifest_path = runtime / "controller-source.json"
240
+ sync.require_owned_regular(manifest_path, "Controller runtime source manifest")
241
+ if (
242
+ manifest_path.stat().st_mode & 0o022
243
+ or manifest_path.stat().st_size > 65536
244
+ or sync.sha256_file(manifest_path) != source_manifest["sha256"]
245
+ ):
246
+ result["errors"].append("Controller source manifest changed during observation; retry read-only check")
247
+ result["status"] = "FAIL" if result["errors"] else "PASS"
248
+ except (OSError, ValueError, KeyError, TypeError, sync.SyncError, subprocess.SubprocessError) as exc:
249
+ result["errors"].append(str(exc))
250
+ return result
251
+
252
+
253
+ def chosen_instruction(directory: Path, fallbacks: list[str]) -> Path | None:
254
+ for name in ("AGENTS.override.md", "AGENTS.md", *fallbacks):
255
+ if Path(name).name != name:
256
+ raise sync.SyncError("instruction fallback must be a filename")
257
+ candidate = directory / name
258
+ if candidate.is_file() and candidate.stat().st_size:
259
+ return candidate
260
+ return None
261
+
262
+
263
+ def _check_per_skill_client_exposure(
264
+ client_label: str,
265
+ client_skills_dir: Path,
266
+ shared_skills_dir: Path,
267
+ warnings: list[str],
268
+ ) -> None:
269
+ if client_skills_dir.is_symlink() and not client_skills_dir.exists():
270
+ warnings.append(f"{client_label} personal skills link is broken")
271
+ return
272
+ if not client_skills_dir.exists():
273
+ return
274
+ if client_skills_dir.resolve() == shared_skills_dir.resolve():
275
+ if (shared_skills_dir / "synced").exists():
276
+ warnings.append(f"{client_label}-synced skills leak into the shared personal skills root")
277
+ return
278
+ for path in sorted(shared_skills_dir.glob("*/SKILL.md")):
279
+ exposed = client_skills_dir / path.parent.name / "SKILL.md"
280
+ if not exposed.is_file() or exposed.resolve() != path.resolve():
281
+ warnings.append(f"{client_label} skills do not expose shared skill {path.parent.name}")
282
+
283
+
284
+ def _inspect_optional_clients(
285
+ agents_root: Path,
286
+ home_dir: Path,
287
+ warnings: list[str],
288
+ references: list[dict[str, Any]],
289
+ ) -> None:
290
+ shared_skills = agents_root / "skills"
291
+ # Gemini CLI reads ~/.gemini/config/skills.json (skill roots / user config) & ~/.gemini/AGENTS.md
292
+ gemini_home = home_dir / ".gemini"
293
+ if gemini_home.is_dir():
294
+ gemini_agents = gemini_home / "AGENTS.md"
295
+ if gemini_agents.is_file():
296
+ references.append(file_identity(gemini_agents))
297
+ gemini_skills_cfg = gemini_home / "config" / "skills.json"
298
+ if gemini_skills_cfg.is_file():
299
+ references.append(file_identity(gemini_skills_cfg))
300
+
301
+ # Cursor (~/.cursor/skills or ~/.cursor/rules) & Qoder (~/.qoder / ~/.qoder-cn)
302
+ for label, client_dir in (
303
+ ("Cursor", home_dir / ".cursor"),
304
+ ("Qoder", home_dir / ".qoder"),
305
+ ("QoderCN", home_dir / ".qoder-cn"),
306
+ ):
307
+ if client_dir.is_dir():
308
+ agent_file = client_dir / "AGENTS.md"
309
+ if agent_file.is_file():
310
+ references.append(file_identity(agent_file))
311
+ _check_per_skill_client_exposure(label, client_dir / "skills", shared_skills, warnings)
312
+
313
+
314
+ def instruction_state(
315
+ repo: Path | None,
316
+ agents_root: Path,
317
+ codex_home: Path,
318
+ claude_home: Path | None = None,
319
+ ) -> dict[str, Any]:
320
+ result: dict[str, Any] = {
321
+ "files": [],
322
+ "warnings": [],
323
+ "errors": [],
324
+ "pending_checkouts": [],
325
+ "session_reload": "reread changed files; the checker cannot verify model context",
326
+ }
327
+ try:
328
+ config_path = codex_home / "config.toml"
329
+ config = tomllib.loads(config_path.read_text()) if config_path.is_file() else {}
330
+ limit = config.get("project_doc_max_bytes", 32768)
331
+ fallbacks = config.get("project_doc_fallback_filenames", [])
332
+ if (
333
+ type(limit) is not int
334
+ or limit <= 0
335
+ or not isinstance(fallbacks, list)
336
+ or any(not isinstance(name, str) or not name for name in fallbacks)
337
+ ):
338
+ raise sync.SyncError("invalid instruction discovery configuration")
339
+ result["configured_limit_bytes"] = limit
340
+ paths: list[Path] = []
341
+ global_path = chosen_instruction(codex_home, [])
342
+ if global_path is not None:
343
+ paths.append(global_path)
344
+ if repo is not None:
345
+ cwd = repo.resolve(strict=True)
346
+ top = Path(readonly_git(cwd, "rev-parse", "--show-toplevel"))
347
+ if not cwd.is_relative_to(top):
348
+ raise sync.SyncError("requested directory is outside resolved checkout")
349
+ for directory in [
350
+ top,
351
+ *[top.joinpath(*cwd.relative_to(top).parts[:n]) for n in range(1, len(cwd.relative_to(top).parts) + 1)],
352
+ ]:
353
+ candidate = chosen_instruction(directory, fallbacks)
354
+ if candidate is not None:
355
+ paths.append(candidate)
356
+ result["checkout"] = str(top)
357
+ result["checkout_head"] = sync.git_head(top)
358
+ raw = readonly_git(top, "worktree", "list", "--porcelain")
359
+ checkouts = [Path(line[9:]) for line in raw.splitlines() if line.startswith("worktree ")]
360
+ if checkouts:
361
+ result["canonical"] = str(checkouts[0])
362
+ reference_names = ("CLAUDE.md", "CLAUDE.local.md", ".claude/CLAUDE.md")
363
+ instruction_names = ["AGENTS.override.md", "AGENTS.md", *fallbacks, *reference_names]
364
+ for checkout in checkouts[:64]:
365
+ if not checkout.is_dir():
366
+ continue
367
+ modified = readonly_git(
368
+ checkout,
369
+ "status",
370
+ "--porcelain=v1",
371
+ "--untracked-files=all",
372
+ "--",
373
+ *instruction_names,
374
+ )
375
+ if modified:
376
+ result["pending_checkouts"].append({"checkout": str(checkout), "changes": modified.splitlines()})
377
+ if len(checkouts) > 64:
378
+ result["warnings"].append("instruction checkout inventory truncated at 64")
379
+ if result["pending_checkouts"]:
380
+ result["warnings"].append("uncommitted instruction changes are not integrated main")
381
+ if checkouts and top != checkouts[0]:
382
+ # Live governance must invalidate the fingerprint even when the branch copy stays old.
383
+ canonical_paths = [checkouts[0] / name for name in reference_names]
384
+ canonical_agent = chosen_instruction(checkouts[0], fallbacks)
385
+ if canonical_agent is not None:
386
+ canonical_paths.insert(0, canonical_agent)
387
+ result["canonical_references"] = [file_identity(path) for path in canonical_paths if path.is_file()]
388
+ local_agent = chosen_instruction(top, fallbacks)
389
+ if canonical_agent and local_agent and sync.sha256_file(canonical_agent) != sync.sha256_file(local_agent):
390
+ result["warnings"].append("checkout AGENTS differs from canonical; review live governance without overwriting branch rules")
391
+ for name in reference_names:
392
+ candidate = top / name
393
+ if candidate.is_file():
394
+ result.setdefault("references", []).append(file_identity(candidate))
395
+ result["files"] = [file_identity(path) for path in paths]
396
+ result["total_bytes"] = sum(item["bytes"] for item in result["files"])
397
+ if result["total_bytes"] > limit:
398
+ result["errors"].append("instruction chain exceeds configured discovery byte limit")
399
+ shared_skills = agents_root / "skills"
400
+ result["skills"] = [
401
+ file_identity(path) for path in sorted(shared_skills.glob("*/SKILL.md")) if path.is_file()
402
+ ]
403
+ claude_home = claude_home if claude_home is not None else codex_home.parent / ".claude"
404
+ _check_per_skill_client_exposure("Claude", claude_home / "skills", shared_skills, result["warnings"])
405
+ bridge = claude_home / "CLAUDE.md"
406
+ if bridge.is_file():
407
+ result.setdefault("references", []).append(file_identity(bridge))
408
+ _inspect_optional_clients(agents_root, codex_home.parent, result["warnings"], result.setdefault("references", []))
409
+ except (OSError, ValueError, TypeError, sync.SyncError, subprocess.SubprocessError) as exc:
410
+ result["errors"].append(str(exc))
411
+ result["status"] = "FAIL" if result["errors"] else "PASS"
412
+ return result
413
+
414
+
415
+ def doctor(
416
+ sources: sync.Sources,
417
+ *,
418
+ agents_root: Path,
419
+ bin_dir: Path | None,
420
+ hooks_dir: Path,
421
+ repo: Path | None,
422
+ codex_home: Path,
423
+ controller: Path | None,
424
+ controller_runtime_root: Path,
425
+ controller_source: Path,
426
+ previous_fingerprint: str | None = None,
427
+ claude_home: Path | None = None,
428
+ ) -> dict[str, Any]:
429
+ results = []
430
+ for name in sources.names():
431
+ try:
432
+ results.append(installed_tool(sources, name, agents_root, bin_dir, hooks_dir))
433
+ except (OSError, ValueError, sync.SyncError, subprocess.SubprocessError) as exc:
434
+ results.append({"tool": name, "status": "FAIL", "errors": [str(exc)]})
435
+ runtime_requirements = sources.compatibility.get("runtime_requirements", {})
436
+ requirements = runtime_requirements.get("worktree-controller") if isinstance(runtime_requirements, dict) else None
437
+ results.append(controller_state(requirements, controller, controller_runtime_root, controller_source, agents_root))
438
+ instructions = instruction_state(repo, agents_root, codex_home, claude_home)
439
+ compatibility_sha = fingerprint(sources.compatibility)
440
+ identity = {
441
+ "compatibility_sha256": compatibility_sha,
442
+ "tools": [{k: v for k, v in item.items() if k not in {"artifact_verification"}} for item in results],
443
+ "instructions": instructions,
444
+ }
445
+ digest = fingerprint(identity)
446
+ return {
447
+ "schema_version": 1,
448
+ "operation": "doctor",
449
+ "status": "PASS" if all(item["status"] == "PASS" for item in [*results, instructions]) else "FAIL",
450
+ "fingerprint": digest,
451
+ "compatibility_sha256": compatibility_sha,
452
+ "toolchain_contract_version": sources.compatibility.get("toolchain_contract_version"),
453
+ "refresh_required": previous_fingerprint != digest,
454
+ "tools": results,
455
+ "instructions": instructions,
456
+ "mutation_performed": False,
457
+ }
458
+
459
+
460
+ def summary(result: dict[str, Any]) -> dict[str, Any]:
461
+ return {
462
+ **{
463
+ k: result[k]
464
+ for k in (
465
+ "schema_version",
466
+ "operation",
467
+ "status",
468
+ "fingerprint",
469
+ "toolchain_contract_version",
470
+ "compatibility_sha256",
471
+ "refresh_required",
472
+ "mutation_performed",
473
+ )
474
+ },
475
+ "tools": [
476
+ {
477
+ k: item.get(k)
478
+ for k in (
479
+ "tool",
480
+ "status",
481
+ "canonical_tool_version",
482
+ "installed_binary_version",
483
+ "software_version",
484
+ "active_commit",
485
+ "cli_contract_version",
486
+ "storage_layout_version",
487
+ "errors",
488
+ )
489
+ }
490
+ for item in result["tools"]
491
+ ],
492
+ "instructions": {
493
+ k: result["instructions"].get(k)
494
+ for k in (
495
+ "status",
496
+ "total_bytes",
497
+ "configured_limit_bytes",
498
+ "warnings",
499
+ "errors",
500
+ "pending_checkouts",
501
+ "session_reload",
502
+ )
503
+ },
504
+ }