kwik-e-gate 0.4.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,646 @@
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import json
5
+ import os
6
+ import shutil
7
+ import tomllib
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ from . import repo_runner
12
+ from .gitstate import ContentReadError, git_dir, repo_identity, snapshot
13
+
14
+ # Single source of truth for pinned Action versions used by the generated workflow.
15
+ # Bump here when dependabot bumps .github/workflows/hermes-quality.yml, so the generator
16
+ # and the tracked file cannot desync (see test_tracked_workflow_matches_the_generator).
17
+ ACTION_VERSIONS = {
18
+ "checkout": "3d3c42e5aac5ba805825da76410c181273ba90b1",
19
+ "setup-python": "5fda3b95a4ea91299a34e894583c3862153e4b97",
20
+ "setup-node": "949feb2413d6458794dcd2491c4babbbce0c15c1",
21
+ "setup-pnpm": "0977fd99725f1db4007ccb2928dbb4e90d06cc86",
22
+ "upload-artifact": "043fb46d1a93c77aae656e7c1c64a875d1fc6a0a",
23
+ }
24
+ # The generated workflow must work before the PyPI packages are published.
25
+ CORE_ACTION_REF = "216f371170ae8e0daeb94ffdcdcd575d7c929a00"
26
+ DEFAULT_PNPM_VERSION = "12.11.2"
27
+ INTEGRATION_FILES = frozenset({
28
+ ".hermes/gate.toml",
29
+ ".hermes/hermes_gate_runner.py",
30
+ ".github/workflows/hermes-quality.yml",
31
+ })
32
+
33
+
34
+ def _contained_file(base: Path, path: Path) -> bool:
35
+ """Allow ordinary files and in-base aliases, including aliases in parents."""
36
+ try:
37
+ relative = path.relative_to(base)
38
+ for depth in range(1, len(relative.parts)):
39
+ parent = base.joinpath(*relative.parts[:depth])
40
+ if parent.is_symlink() and not parent.is_dir():
41
+ return False
42
+ if parent.exists() and not parent.is_dir():
43
+ return False
44
+ if path.is_symlink() and not path.is_file():
45
+ return False
46
+ if path.exists() and not path.is_file():
47
+ return False
48
+ return path.resolve(strict=False).is_relative_to(base.resolve(strict=True))
49
+ except (OSError, RuntimeError, ValueError):
50
+ return False
51
+
52
+
53
+ def _metadata_state_safe(root: Path) -> bool:
54
+ metadata = git_dir(root)
55
+ state = metadata / "kwik-e-gate"
56
+ manifest = state / "install.json"
57
+ baseline = state / "baseline.json"
58
+ backups = state / "install-backup"
59
+ return (
60
+ not state.is_symlink()
61
+ and not manifest.is_symlink()
62
+ and not baseline.is_symlink()
63
+ and not backups.is_symlink()
64
+ and _contained_file(metadata, manifest)
65
+ and _contained_file(metadata, baseline)
66
+ and all(
67
+ not (backups / relative).is_symlink()
68
+ and _contained_file(metadata, backups / relative)
69
+ for relative in INTEGRATION_FILES
70
+ )
71
+ )
72
+
73
+
74
+ def initialize(root: Path, *, force: bool = False, adapter: str = "native") -> dict[str, Any]:
75
+ if adapter not in {"native", "pygate", "quick-gate"}:
76
+ return {"status": "ERROR", "reason": f"unsupported adapter: {adapter}"}
77
+ hermes = root / ".hermes"
78
+ profile = hermes / "gate.toml"
79
+ runner = hermes / "hermes_gate_runner.py"
80
+ workflow = root / ".github" / "workflows" / "hermes-quality.yml"
81
+ targets = [profile, runner, workflow]
82
+ dangling = [path for path in targets if path.is_symlink() and not path.exists()]
83
+ if dangling:
84
+ return {
85
+ "status": "PARKED",
86
+ "reason": "refusing to overwrite dangling integration symlink(s); preserve them manually",
87
+ "existing": [str(path.relative_to(root)) for path in dangling],
88
+ }
89
+ unsafe = [path for path in targets if not _contained_file(root, path)]
90
+ if unsafe:
91
+ return {
92
+ "status": "PARKED",
93
+ "reason": "refusing integration path outside this repository or without a regular file",
94
+ "existing": [str(path.relative_to(root)) for path in unsafe],
95
+ }
96
+ existing = [path for path in targets if path.exists()]
97
+ if existing and not force:
98
+ return {
99
+ "status": "PARKED",
100
+ "reason": "refusing to overwrite existing integration; rerun with --force after review",
101
+ "existing": [str(path.relative_to(root)) for path in existing],
102
+ }
103
+ try:
104
+ preflight_snapshot = snapshot(root)
105
+ except ContentReadError as exc:
106
+ return {"status": "PARKED", "reason": f"cannot read complete repository bytes: {exc}"}
107
+ if not _metadata_state_safe(root):
108
+ return {"status": "PARKED", "reason": "Gate state leaves the Git directory"}
109
+ if is_adopted(root):
110
+ return {
111
+ "status": "PARKED",
112
+ "reason": "Gate is already installed; preserve its original backup and manifest",
113
+ }
114
+ backup_root = git_dir(root) / "kwik-e-gate" / "install-backup"
115
+ metadata = git_dir(root)
116
+ unsafe_backups = [
117
+ backup_root / relative for relative in INTEGRATION_FILES
118
+ if (backup_root / relative).is_symlink()
119
+ or not _contained_file(metadata, backup_root / relative)
120
+ ]
121
+ if unsafe_backups:
122
+ return {
123
+ "status": "PARKED",
124
+ "reason": "refusing backup path outside Git metadata or through a backup symlink",
125
+ "existing": [str(path.relative_to(backup_root)) for path in unsafe_backups],
126
+ }
127
+ # An older install or interrupted rollback may have left backups behind.
128
+ # Reuse only a byte-identical copy of a file still present in the checkout;
129
+ # otherwise its original ownership cannot be inferred safely.
130
+ for relative in INTEGRATION_FILES:
131
+ backup = backup_root / relative
132
+ if not backup.exists():
133
+ continue
134
+ target = root / relative
135
+ try:
136
+ if not target.is_file() or backup.read_bytes() != target.read_bytes():
137
+ return {
138
+ "status": "PARKED",
139
+ "reason": f"stale backup without matching owner file: {relative}",
140
+ }
141
+ except OSError:
142
+ return {"status": "PARKED", "reason": f"backup unreadable: {relative}"}
143
+ backup_root.mkdir(parents=True, exist_ok=True)
144
+ backup_manifest: dict[str, str] = {}
145
+ for path in existing:
146
+ relative = path.relative_to(root)
147
+ destination = backup_root / relative
148
+ destination.parent.mkdir(parents=True, exist_ok=True)
149
+ shutil.copy2(path, destination)
150
+ backup_manifest[str(relative)] = hashlib.sha256(path.read_bytes()).hexdigest()
151
+
152
+ hermes.mkdir(parents=True, exist_ok=True)
153
+ workflow.parent.mkdir(parents=True, exist_ok=True)
154
+ source = Path(repo_runner.__file__).read_bytes()
155
+ intended = {
156
+ profile: _detected_profile(root, adapter=adapter).encode("utf-8"),
157
+ runner: source,
158
+ workflow: _workflow(root).encode("utf-8"),
159
+ }
160
+ expected_hashes = {
161
+ str(path.relative_to(root)): hashlib.sha256(content).hexdigest()
162
+ for path, content in intended.items()
163
+ }
164
+ expected_snapshot = {
165
+ str(path.relative_to(root)): (
166
+ f"SYMLINK:{os.readlink(path)}:FILE:{expected_hashes[str(path.relative_to(root))]}"
167
+ if path.is_symlink() else expected_hashes[str(path.relative_to(root))]
168
+ )
169
+ for path in targets
170
+ }
171
+ for path, content in intended.items():
172
+ path.write_bytes(content)
173
+ runner_sha = hashlib.sha256(source).hexdigest()
174
+ manifest = {
175
+ "schema": "hermes-gate/install-v1",
176
+ "repository": repo_identity(root),
177
+ "files": expected_hashes,
178
+ "runner_sha256": runner_sha,
179
+ "runner_version": repo_runner.RUNNER_VERSION,
180
+ "backups": backup_manifest,
181
+ "rollback": "kwik-e-gate uninstall-repo",
182
+ }
183
+ try:
184
+ generated = snapshot(root, [str(path.relative_to(root)) for path in targets])
185
+ if generated != expected_snapshot:
186
+ raise ContentReadError("generated integration differs from intended bytes")
187
+ except ContentReadError as exc:
188
+ restored, removed, rollback_error = _rollback_generated_targets(
189
+ root, targets, existing, backup_root
190
+ )
191
+ if rollback_error:
192
+ return {
193
+ "status": "ERROR",
194
+ "reason": (
195
+ "generated integration could not be bound to complete bytes and rollback failed: "
196
+ f"{rollback_error}; preserve the checkout before retrying"
197
+ ),
198
+ }
199
+ return {
200
+ "status": "PARKED",
201
+ "reason": (
202
+ "generated integration could not be bound to complete bytes and was rolled back: "
203
+ f"{exc}; restored {restored}, removed {removed}; recover storage, then rerun"
204
+ ),
205
+ }
206
+ baseline = {"repository": repo_identity(root), "dirty": {**preflight_snapshot, **generated}}
207
+ state_path = git_dir(root) / "kwik-e-gate" / "baseline.json"
208
+ state_path.parent.mkdir(parents=True, exist_ok=True)
209
+ state_path.write_text(json.dumps(baseline, sort_keys=True) + "\n", encoding="utf-8")
210
+ manifest_path = _install_manifest_path(root)
211
+ manifest_path.parent.mkdir(parents=True, exist_ok=True)
212
+ manifest_path.write_text(
213
+ json.dumps(manifest, indent=2, sort_keys=True) + "\n", encoding="utf-8"
214
+ )
215
+ return {
216
+ "status": "PASS",
217
+ "profile": str(profile),
218
+ "runner": str(runner),
219
+ "runner_sha256": runner_sha,
220
+ "workflow": str(workflow),
221
+ "adapter_status": "NATIVE_DEFAULT" if adapter == "native" else "EXPLICIT_ADAPTER",
222
+ "reason": "profile written; review declared commands before running; tools are not installed",
223
+ }
224
+
225
+
226
+ def _rollback_generated_targets(
227
+ root: Path, targets: list[Path], existing: list[Path], backup_root: Path
228
+ ) -> tuple[list[str], list[str], str | None]:
229
+ restored: list[str] = []
230
+ removed: list[str] = []
231
+ existing_set = set(existing)
232
+ if not _metadata_state_safe(root):
233
+ return restored, removed, "Gate state leaves the Git directory"
234
+ for target in targets:
235
+ relative = target.relative_to(root)
236
+ backup = backup_root / relative
237
+ if not _contained_file(root, target):
238
+ return restored, removed, f"unsafe restore path for {relative}"
239
+ if target in existing_set and (
240
+ backup.is_symlink() or not _contained_file(git_dir(root), backup)
241
+ ):
242
+ return restored, removed, f"unsafe backup path for {relative}"
243
+ try:
244
+ for target in targets:
245
+ relative = target.relative_to(root)
246
+ if target in existing_set:
247
+ backup = backup_root / relative
248
+ if not backup.is_file():
249
+ return restored, removed, f"missing backup for {relative}"
250
+ shutil.copy2(backup, target)
251
+ restored.append(str(relative))
252
+ elif target.exists():
253
+ target.unlink()
254
+ removed.append(str(relative))
255
+ except OSError as exc:
256
+ return restored, removed, str(exc)
257
+ return restored, removed, None
258
+
259
+
260
+ def uninstall(root: Path) -> dict[str, Any]:
261
+ if not _metadata_state_safe(root):
262
+ return {"status": "PARKED", "reason": "Gate state leaves the Git directory"}
263
+ manifest_path = _install_manifest_path(root)
264
+ try:
265
+ manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
266
+ except (FileNotFoundError, json.JSONDecodeError, OSError):
267
+ return {"status": "NOT_CONFIGURED", "reason": "no install manifest"}
268
+ backup_root = git_dir(root) / "kwik-e-gate" / "install-backup"
269
+ files = manifest.get("files")
270
+ if not isinstance(files, dict) or set(files) != INTEGRATION_FILES:
271
+ return {"status": "NOT_CONFIGURED", "reason": "malformed install manifest"}
272
+ recorded_backups = manifest.get("backups", {})
273
+ if (not isinstance(recorded_backups, dict)
274
+ or any(key not in files or not isinstance(value, str)
275
+ for key, value in recorded_backups.items())):
276
+ return {"status": "NOT_CONFIGURED", "reason": "malformed install backups"}
277
+
278
+ # Never restore/remove an early target before proving that every generated
279
+ # target is still the exact installed byte sequence. A later local edit
280
+ # must park the entire rollback, not leave a partially restored integration.
281
+ planned: list[tuple[str, Path, Path]] = []
282
+ for relative, installed_sha in files.items():
283
+ if (not isinstance(relative, str) or relative not in INTEGRATION_FILES
284
+ or not isinstance(installed_sha, str)):
285
+ return {"status": "NOT_CONFIGURED", "reason": "malformed install manifest"}
286
+ target = root / relative
287
+ backup = backup_root / relative
288
+ if not _contained_file(root, target):
289
+ return {"status": "PARKED", "reason": f"unsafe installed path: {relative}"}
290
+ if backup.is_symlink() or not _contained_file(git_dir(root), backup):
291
+ return {"status": "PARKED", "reason": f"unsafe backup path: {relative}"}
292
+ if target.exists() and hashlib.sha256(target.read_bytes()).hexdigest() != installed_sha:
293
+ return {
294
+ "status": "PARKED",
295
+ "reason": f"installed file changed: {relative}; preserve it manually",
296
+ }
297
+ planned.append((relative, target, backup))
298
+
299
+ # An owner backup is an obligation, not an optional hint. Validate every one
300
+ # before restoring or removing any generated file.
301
+ for relative, _target, backup in planned:
302
+ expected = recorded_backups.get(relative)
303
+ if expected is None:
304
+ if backup.exists():
305
+ return {"status": "PARKED", "reason": f"unrecorded backup: {relative}"}
306
+ continue
307
+ try:
308
+ if not backup.is_file() or hashlib.sha256(backup.read_bytes()).hexdigest() != expected:
309
+ return {"status": "PARKED", "reason": f"backup changed: {relative}"}
310
+ except OSError:
311
+ return {"status": "PARKED", "reason": f"backup unreadable: {relative}"}
312
+
313
+ restored: list[str] = []
314
+ removed: list[str] = []
315
+ for relative, target, backup in planned:
316
+ if backup.exists():
317
+ target.parent.mkdir(parents=True, exist_ok=True)
318
+ shutil.copy2(backup, target)
319
+ restored.append(relative)
320
+ elif target.exists():
321
+ target.unlink()
322
+ removed.append(relative)
323
+ manifest_path.unlink(missing_ok=True)
324
+ # The owner bytes are back in the checkout. These copies are no longer an
325
+ # install obligation; leaving them would poison a later fresh install.
326
+ try:
327
+ for relative, _target, backup in planned:
328
+ if relative in recorded_backups:
329
+ backup.unlink()
330
+ except OSError as exc:
331
+ return {
332
+ "status": "ERROR",
333
+ "reason": f"integration restored but backup cleanup failed: {exc}",
334
+ "restored": restored,
335
+ "removed": removed,
336
+ }
337
+ return {"status": "PASS", "restored": restored, "removed": removed}
338
+
339
+
340
+ def verify_runner(root: Path) -> tuple[bool, str]:
341
+ if not _metadata_state_safe(root):
342
+ return False, "Gate state leaves the Git directory"
343
+ manifest_path = _install_manifest_path(root)
344
+ runner = root / ".hermes" / "hermes_gate_runner.py"
345
+ try:
346
+ manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
347
+ actual = hashlib.sha256(runner.read_bytes()).hexdigest()
348
+ except (FileNotFoundError, json.JSONDecodeError, OSError) as exc:
349
+ return False, str(exc)
350
+ expected = str(manifest.get("runner_sha256", ""))
351
+ return actual == expected, actual
352
+
353
+
354
+ def _javascript_package_manager(root: Path) -> str:
355
+ return "pnpm" if (root / "pnpm-lock.yaml").exists() else "npm"
356
+
357
+
358
+ def _detected_profile(root: Path, *, adapter: str = "native") -> str:
359
+ python = (root / "pyproject.toml").is_file() or (root / "requirements.txt").is_file()
360
+ javascript = (root / "package.json").is_file()
361
+ fast: list[tuple[str, list[str], float, list[str]]] = []
362
+ full: list[tuple[str, list[str], float, list[str]]] = []
363
+ repair: list[tuple[str, list[str], float, list[str]]] = []
364
+ adapter_status = "NATIVE_DEFAULT" if adapter == "native" else "EXPLICIT_ADAPTER"
365
+ reviewer = "coderabbit"
366
+ if python:
367
+ fast.append(
368
+ (
369
+ "python-parse",
370
+ [
371
+ "python3",
372
+ "-c",
373
+ "import ast,pathlib,sys; [ast.parse(pathlib.Path(p).read_bytes(), filename=p) for p in sys.argv[1:]]",
374
+ "{files}",
375
+ ],
376
+ 6.0,
377
+ ["**/*.py"],
378
+ )
379
+ )
380
+ if (root / "src").is_dir():
381
+ pytest_argv = [
382
+ "python3",
383
+ "-c",
384
+ "import sys; sys.path.insert(0, 'src'); import pytest; raise SystemExit(pytest.main(['-q']))",
385
+ ]
386
+ else:
387
+ pytest_argv = ["python3", "-m", "pytest", "-q"]
388
+ full.append(("pytest", pytest_argv, 180.0, ["**/*"]))
389
+ if shutil.which("ruff"):
390
+ fast.insert(0, ("ruff", ["ruff", "check", "{files}"], 6.0, ["**/*.py"]))
391
+ full.insert(0, ("ruff", ["ruff", "check", "."], 60.0, ["**/*"]))
392
+ repair.append(("ruff-fix", ["ruff", "check", "--fix", "{files}"], 8.0, ["**/*.py"]))
393
+ if javascript:
394
+ package = _package_scripts(root / "package.json")
395
+ manager = _javascript_package_manager(root)
396
+ if "lint" in package:
397
+ fast.append(
398
+ (
399
+ "lint",
400
+ [manager, "run", "lint"],
401
+ 8.0,
402
+ ["**/*.js", "**/*.jsx", "**/*.ts", "**/*.tsx", "**/*.mjs", "**/*.cjs",
403
+ "**/*.vue", "**/*.svelte", "package.json", "**/*.config.*", ".eslintrc*"],
404
+ )
405
+ )
406
+ full.append(("lint", [manager, "run", "lint"], 120.0, ["**/*"]))
407
+ if "typecheck" in package:
408
+ full.append(("typecheck", [manager, "run", "typecheck"], 120.0, ["**/*"]))
409
+ if "test" in package:
410
+ full.append(("test", [manager, "test"], 180.0, ["**/*"]))
411
+ if "build" in package:
412
+ full.append(("build", [manager, "run", "build"], 180.0, ["**/*"]))
413
+ diff_argv = ["python3", ".hermes/hermes_gate_runner.py", "diff-check", "{files}"]
414
+ if not full:
415
+ full.append(("diff-check", diff_argv, 10.0, ["**/*"]))
416
+ lines = [
417
+ "version = 1",
418
+ "",
419
+ "[gate]",
420
+ "fast_budget_seconds = 8.0",
421
+ "full_required_local = false",
422
+ "review_required = false",
423
+ f'adapter_status = "{adapter_status}"',
424
+ 'exclusions = [".git/**", ".hermes/hermes_gate_runner.py", ".pytest_cache/**", ".ruff_cache/**", "**/__pycache__/**", "vendor/**", "node_modules/**", "dist/**", "build/**"]',
425
+ "",
426
+ "[adapter]",
427
+ f"enabled = {'false' if adapter == 'native' else 'true'}",
428
+ f'name = "{adapter}"',
429
+ ("argv = []" if adapter == "native" else 'argv = ["pygate"]'
430
+ if adapter == "pygate" else 'argv = ["npx", "--no-install", "quick-gate"]'),
431
+ 'minimum_version = ""' if adapter == "native" else 'minimum_version = "0.3.2"',
432
+ "",
433
+ "[lintlang]",
434
+ f"enabled = {'true' if shutil.which('lintlang') else 'false'}",
435
+ 'argv = ["lintlang", "scan", "--format", "json", "--fail-on", "review", "{files}"]',
436
+ 'trigger_globs = ["**/AGENTS.md", "**/CLAUDE.md", "**/prompts/**", "**/*.prompt", ".codex/**", ".claude/**"]',
437
+ "timeout_seconds = 4.0",
438
+ 'blocking_threshold = "MEDIUM"',
439
+ "",
440
+ "[review]",
441
+ 'provider = "coderabbit"',
442
+ f"argv = {json.dumps([reviewer, 'review', '--agent'])}",
443
+ "timeout_seconds = 180.0",
444
+ 'material_severities = ["critical", "major"]',
445
+ 'material_categories = ["correctness", "security", "data-loss", "concurrency", "api-contract"]',
446
+ "fallback_argv = []",
447
+ ]
448
+ fast.append(("diff-check", diff_argv, 4.0, ["**/*"]))
449
+ for table, commands in (("fast", fast), ("full", full), ("repair", repair)):
450
+ for name, argv, timeout, globs in commands:
451
+ lines.extend(
452
+ [
453
+ "",
454
+ f"[[{table}]]",
455
+ f'name = "{name}"',
456
+ f"argv = {json.dumps(argv)}",
457
+ f"timeout_seconds = {timeout}",
458
+ f"globs = {json.dumps(globs)}",
459
+ ]
460
+ )
461
+ return "\n".join(lines) + "\n"
462
+
463
+
464
+ def _workflow(root: Path) -> str:
465
+ steps = [
466
+ f" - uses: actions/checkout@{ACTION_VERSIONS['checkout']}",
467
+ " with:",
468
+ " # The gate compares the pull request base with HEAD, so the base commit",
469
+ " # has to be in the checkout.",
470
+ " fetch-depth: 0",
471
+ " # The gate only reads the checkout. Do not leave the workflow token in",
472
+ " # .git/config where every later step and declared stage could read it.",
473
+ " persist-credentials: false",
474
+ f" - uses: actions/setup-python@{ACTION_VERSIONS['setup-python']}",
475
+ " with:",
476
+ " python-version: '3.12'",
477
+ ]
478
+ if (root / "pyproject.toml").is_file():
479
+ install_target = ".[test]" if _has_test_extra(root / "pyproject.toml") else "."
480
+ tools: list[str] = []
481
+ if install_target == ".":
482
+ if shutil.which("ruff"):
483
+ tools.append("ruff")
484
+ if shutil.which("pytest") or (root / "tests").is_dir():
485
+ tools.append("pytest")
486
+ tool_suffix = " " + " ".join(tools) if tools else ""
487
+ steps.extend(
488
+ [
489
+ " - name: Install project and declared gate tools",
490
+ f" run: python3 -m pip install -e '{install_target}'{tool_suffix}",
491
+ ]
492
+ )
493
+ if (root / "package.json").is_file():
494
+ steps.extend(
495
+ [
496
+ f" - uses: actions/setup-node@{ACTION_VERSIONS['setup-node']}",
497
+ " with:",
498
+ " node-version: '24'",
499
+ ]
500
+ )
501
+ if _javascript_package_manager(root) == "pnpm":
502
+ steps.extend([
503
+ f" - uses: pnpm/action-setup@{ACTION_VERSIONS['setup-pnpm']}",
504
+ " with:",
505
+ " run_install: false",
506
+ ])
507
+ if not _declares_pnpm_version(root / "package.json"):
508
+ steps.append(f" version: '{DEFAULT_PNPM_VERSION}'")
509
+ install_command = "pnpm install --frozen-lockfile"
510
+ else:
511
+ install_command = "npm ci" if (root / "package-lock.json").is_file() else "npm install"
512
+ steps.extend([
513
+ " - name: Install JavaScript dependencies",
514
+ f" run: {install_command}",
515
+ ])
516
+ try:
517
+ own_project = tomllib.loads((root / "pyproject.toml").read_text()).get("project", {})
518
+ except (OSError, tomllib.TOMLDecodeError):
519
+ own_project = {}
520
+ if own_project.get("name") == "kwik-e-gate":
521
+ # Exercise this repository's installed engine when gating Kwik-e-gate itself.
522
+ steps.extend(
523
+ [
524
+ # A hosted checkout has no worktree, index or untracked changes, so the default
525
+ # local scope selects nothing and every file-driven stage would report a pass
526
+ # over zero bytes. Name the range explicitly instead.
527
+ " - name: Run declared full gate against the pull request range",
528
+ " if: github.event_name == 'pull_request'",
529
+ " env:",
530
+ " HERMES_GATE_BASE: ${{ github.event.pull_request.base.sha }}",
531
+ ' run: kwik-e-gate run --mode full --output "$RUNNER_TEMP/kwik-e-gate-receipt.json"',
532
+ " - name: Run declared full gate against every committed byte",
533
+ " if: github.event_name != 'pull_request'",
534
+ ' run: kwik-e-gate run --mode full --output "$RUNNER_TEMP/kwik-e-gate-receipt.json"',
535
+ ]
536
+ )
537
+ receipt_path = "${{ runner.temp }}/kwik-e-gate-receipt.json"
538
+ upload_condition = "always()"
539
+ else:
540
+ steps.extend([
541
+ " - name: Resolve the gate comparison base",
542
+ " id: gate-base",
543
+ " env:",
544
+ " EVENT_BASE: ${{ github.event.pull_request.base.sha || github.event.before }}",
545
+ " run: |",
546
+ ' base="$EVENT_BASE"',
547
+ ' case "$base" in',
548
+ " ''|0000000000000000000000000000000000000000)",
549
+ ' base=$(git rev-parse --verify HEAD^ 2>/dev/null || true) ;;',
550
+ " esac",
551
+ ' printf "base=%s\\n" "$base" >> "$GITHUB_OUTPUT"',
552
+ " - name: Run the declared full gate",
553
+ f" uses: hermes-labs-ai/kwik-e-gate/.github/actions/kwik-e-gate@{CORE_ACTION_REF}",
554
+ " id: gate",
555
+ " with:",
556
+ " mode: full",
557
+ " python-version: '3.12'",
558
+ " base: ${{ steps.gate-base.outputs.base }}",
559
+ ])
560
+ receipt_path = "${{ steps.gate.outputs.receipt-path }}"
561
+ upload_condition = "always() && steps.gate.outputs.receipt-path != ''"
562
+ steps.extend(
563
+ [
564
+ " - name: Preserve the receipt",
565
+ f" if: {upload_condition}",
566
+ f" uses: actions/upload-artifact@{ACTION_VERSIONS['upload-artifact']}",
567
+ " with:",
568
+ " name: kwik-e-gate-receipt",
569
+ f" path: {receipt_path}",
570
+ " if-no-files-found: warn",
571
+ ]
572
+ )
573
+ return "\n".join(
574
+ [
575
+ "name: Kwik-e-gate",
576
+ "",
577
+ "on:",
578
+ " pull_request:",
579
+ " push:",
580
+ " branches: [main]",
581
+ " workflow_dispatch:",
582
+ "",
583
+ "permissions:",
584
+ " contents: read",
585
+ "",
586
+ "jobs:",
587
+ " full:",
588
+ " runs-on: ubuntu-latest",
589
+ " steps:",
590
+ *steps,
591
+ "",
592
+ ]
593
+ )
594
+
595
+
596
+ def _declares_pnpm_version(path: Path) -> bool:
597
+ try:
598
+ package = json.loads(path.read_text(encoding="utf-8"))
599
+ except (OSError, ValueError):
600
+ return False
601
+ if not isinstance(package, dict):
602
+ return False
603
+ manager = package.get("packageManager")
604
+ if isinstance(manager, str) and manager.startswith("pnpm@") and manager[5:].strip():
605
+ return True
606
+ engines = package.get("devEngines")
607
+ declared = engines.get("packageManager") if isinstance(engines, dict) else None
608
+ return (
609
+ isinstance(declared, dict)
610
+ and declared.get("name") == "pnpm"
611
+ and isinstance(declared.get("version"), str)
612
+ and bool(declared["version"].strip())
613
+ )
614
+
615
+
616
+ def _package_scripts(path: Path) -> dict[str, str]:
617
+ try:
618
+ raw = json.loads(path.read_text(encoding="utf-8"))
619
+ except (OSError, json.JSONDecodeError):
620
+ return {}
621
+ scripts = raw.get("scripts", {}) if isinstance(raw, dict) else {}
622
+ return scripts if isinstance(scripts, dict) else {}
623
+
624
+
625
+ def _install_manifest_path(root: Path) -> Path:
626
+ return git_dir(root) / "kwik-e-gate" / "install.json"
627
+
628
+
629
+ def is_adopted(root: Path) -> bool:
630
+ """Keep existing enrollments fail-closed, including pre-split manifests."""
631
+ markers = (
632
+ _install_manifest_path(root),
633
+ root / ".hermes" / "install.json",
634
+ git_dir(root) / "hermes-gate" / "install.json",
635
+ )
636
+ return any(path.exists() or path.is_symlink() for path in markers)
637
+
638
+
639
+ def _has_test_extra(path: Path) -> bool:
640
+ try:
641
+ raw = tomllib.loads(path.read_text(encoding="utf-8"))
642
+ except (OSError, tomllib.TOMLDecodeError):
643
+ return False
644
+ project = raw.get("project", {}) if isinstance(raw, dict) else {}
645
+ optional = project.get("optional-dependencies", {}) if isinstance(project, dict) else {}
646
+ return isinstance(optional, dict) and isinstance(optional.get("test"), list)