Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .agents/skills/create-github-pr/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ Use the `sync-agent-infra` skill's maintenance map to identify related skill upd

Use the verification guidance in `CONTRIBUTING.md` to select checks for the changed files and behavior. Guidance, skills, and template changes need applicable Markdown, YAML, link, and consistency checks. Run Rust or SDK suites when those components or their dependencies can be affected. Shared APIs, schemas, dependencies, and build changes may require broader checks even when component source files are unchanged.

`mise run ci` and `mise run pre-commit` are broad convenience tasks, not blanket PR prerequisites. Broaden validation only for a concrete remaining risk or failed check, and report what actually ran.
`mise run pre-commit` selects checks from staged paths. `mise run ci` and `mise run pre-commit:full` are broad convenience tasks, not blanket PR prerequisites. Broaden validation only for a concrete remaining risk or failed check, and report what actually ran.

### Verify Branch State

Expand Down
2 changes: 1 addition & 1 deletion .agents/skills/tui-development/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -609,7 +609,7 @@ cargo clippy -p openshell-tui

### Verification

Follow Choose Verification for the Change in `CONTRIBUTING.md`. Select format, lint, and tests for the affected TUI behavior and its dependencies. Use `mise run pre-commit` when its broader scope is warranted.
Follow Choose Verification for the Change in `CONTRIBUTING.md`. Select format, lint, and tests for the affected TUI behavior and its dependencies. `mise run pre-commit` selects checks from staged paths; use `mise run pre-commit:full` when its broader scope is warranted.

### Gateway changes

Expand Down
17 changes: 16 additions & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -539,7 +539,22 @@ For contributor guidance, skills, Markdown, and issue or PR templates, validate

For code changes, run tests for the affected crates or SDKs and their dependent behavior. For sandbox, policy, or deployment infrastructure changes, run the relevant E2E lane. Broaden verification when the change spans components, focused checks fail, or a concrete regression risk remains.

`mise run ci` runs the full repository checks, and `mise run pre-commit` runs broad formatting and lint checks. Use them when that scope is warranted; they are not blanket prerequisites for every change. Report what actually ran and any relevant limitation in the PR. Stop once the checks needed for the change have passed.
`mise run pre-commit` selects formatting and lint checks from staged paths. Existing hooks that invoke this task need no reinstall. The mapping lives in `tasks/scripts/pre_commit.py`:

| Staged paths | Checks selected |
| --- | --- |
| Markdown (`.md`, `.mdx`) | Markdown format, lint, and Mermaid validation |
| Rust (`.rs`, `Cargo.toml`, `Cargo.lock`) | Rust format, lockfiles, Clippy, and license headers |
| Python (`.py`) | Python format, lint (including its proto-generation dependency), and license headers |
| `deploy/helm/**` | Helm lint, generated chart docs, and license headers; Markdown checks also apply to chart READMEs |
| Protobuf (`.proto`) | Proto lint, Rust and Python checks, and license headers |
| Shared check scripts, task/tool configuration, or unrecognized paths | Full formatting and lint checks |

Mixed changes select the union of their checks. Renames consider both paths, deletions still select their area, and an empty staged set runs no checks. Selection reads the Git index directly, ignoring any legacy `STAGED` environment variable.

Inspect selection with `mise run pre-commit --dry-run`. Run all formatting and lint checks with `mise run pre-commit:full`, regardless of staged paths. Selected tasks still operate on their existing working-tree scope and may format unstaged files; this does not validate an isolated snapshot of partially staged content. Review and restage formatting changes before committing. CI checks retain their existing scope.

`mise run ci` runs the full repository checks. Use broad checks when that scope is warranted; they are not blanket prerequisites for every change. Report what actually ran and any relevant limitation in the PR. Stop once the checks needed for the change have passed.

### Commit Messages

Expand Down
7 changes: 6 additions & 1 deletion tasks/ci.toml
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,11 @@ depends = ["ci"]
hide = true

["pre-commit"]
description = "Run lint, formatting, and license checks"
description = "Run formatting and lint checks relevant to staged paths"
run = "uv run --no-project python tasks/scripts/pre_commit.py"
hide = true

["pre-commit:full"]
description = "Run all formatting, lint, and license checks"
depends = ["fmt", "lint"]
hide = true
93 changes: 93 additions & 0 deletions tasks/scripts/pre_commit.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
# SPDX-License-Identifier: Apache-2.0

"""Select existing pre-commit task groups from staged Git paths."""

import argparse
import os
import subprocess
import sys
from pathlib import Path, PurePosixPath

FULL = {"pre-commit:full"}
RUST = {"rust:format", "rust:format:check", "rust:lockfiles:check", "rust:lint"}
PYTHON = {"python:format", "python:format:check", "python:lint"}
MARKDOWN = {"markdown:format", "markdown:lint"}
HELM = {"helm:lint", "helm:docs:check"}


def tasks_for_path(path: str) -> set[str]:
"""Keep the path-to-check mapping here; unrecognized inputs run everything."""
if path in {
"tasks/scripts/check_cargo_lockfile_alignment.py",
"tasks/scripts/pre_commit.py",
"scripts/update_license_headers.py",
} or path.startswith("scripts/lint-mermaid/"):
return FULL

name = PurePosixPath(path)
tasks: set[str] = set()
if name.suffix in {".md", ".mdx"}:
tasks.update(MARKDOWN)
if name.suffix == ".rs" or name.name in {"Cargo.toml", "Cargo.lock"}:
tasks.update(RUST | {"license:check"})
if name.suffix == ".py":
tasks.update(PYTHON | {"license:check"})
if path.startswith("deploy/helm/"):
tasks.update(HELM | {"license:check"})
if name.suffix == ".proto":
tasks.update(RUST | PYTHON | {"proto:lint", "license:check"})
return tasks or FULL


def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--full", action="store_true", help="Run all checks")
parser.add_argument(
"--dry-run",
action="store_true",
help="Print selected tasks without running them",
)
args = parser.parse_args()

try:
root = Path(
os.fsdecode(
subprocess.check_output(["git", "rev-parse", "--show-toplevel"])
).strip()
)
if args.full:
tasks = FULL
else:
# No explicit HEAD: Git also supports an initial, unborn branch.
# Disable rename detection so both old and new paths select checks.
staged = subprocess.check_output(
["git", "diff", "--cached", "--name-only", "--no-renames", "-z"],
cwd=root,
)
tasks: set[str] = set()
for raw_path in staged.split(b"\0"):
if raw_path:
tasks.update(tasks_for_path(os.fsdecode(raw_path)))
if "pre-commit:full" in tasks:
tasks = FULL

if not tasks:
print("No staged changes; no pre-commit checks selected.")
return 0
print("Pre-commit tasks: " + " ".join(sorted(tasks)), flush=True)
if args.dry_run:
return 0

command = ["mise", "run"]
for task in sorted(tasks):
if len(command) > 2:
command.append(":::")
command.append(task)
return subprocess.run(command, cwd=root, check=False).returncode
except (OSError, subprocess.CalledProcessError) as error:
print(f"pre-commit: {error}", file=sys.stderr)
return 1


if __name__ == "__main__":
sys.exit(main())
243 changes: 243 additions & 0 deletions tasks/scripts/pre_commit_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,243 @@
# SPDX-License-Identifier: Apache-2.0

"""Exercise pre-commit selection against real Git indexes."""

import os
import shutil
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path

SCRIPT = Path(__file__).with_name("pre_commit.py")


class PreCommitTest(unittest.TestCase):
def setUp(self):
self.directory = tempfile.TemporaryDirectory()
self.addCleanup(self.directory.cleanup)
self.root = Path(self.directory.name)
self.env = os.environ.copy()
# A hook can run these tests with its own repository/index in the env.
for name in ("GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE"):
self.env.pop(name, None)
self.git("init", "-q")

def git(self, *args):
return subprocess.run(
["git", *args],
cwd=self.root,
env=self.env,
check=True,
capture_output=True,
)

def stage(self, path):
target = self.root / path
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text("example\n")
self.git("add", "--", path)

def commit(self):
self.git(
"-c",
"user.name=Test",
"-c",
"user.email=test@example.invalid",
"-c",
"commit.gpgsign=false",
"-c",
"core.hooksPath=/dev/null",
"commit",
"-qm",
"test fixture",
)

def run_selector(self, *args):
return subprocess.run(
[sys.executable, str(SCRIPT), *args],
cwd=self.root,
env=self.env,
capture_output=True,
text=True,
)

def selected(self, *args):
result = self.run_selector("--dry-run", *args)
self.assertEqual(result.returncode, 0, result.stderr)
return set(result.stdout.removeprefix("Pre-commit tasks: ").split())

def test_markdown_only_initial_commit_skips_other_languages(self):
self.stage("rfc/design with spaces.md")
self.env["STAGED"] = "crates/example/src/lib.rs"
self.assertEqual(self.selected(), {"markdown:format", "markdown:lint"})

@unittest.skipIf(os.name == "nt", "Windows filenames cannot contain newlines")
def test_newline_in_filename_preserves_path_boundaries(self):
self.stage("rfc/design\nwith newline.md")
self.assertEqual(self.selected(), {"markdown:format", "markdown:lint"})

def test_rust_source_selects_rust_checks(self):
self.stage("crates/example/src/lib.rs")
self.assertEqual(
self.selected(),
{
"license:check",
"rust:format",
"rust:format:check",
"rust:lockfiles:check",
"rust:lint",
},
)

def test_manifests_and_lockfiles_select_rust_checks(self):
for path in ("Cargo.toml", "Cargo.lock", "tests/testkit/Cargo.toml"):
with self.subTest(path=path):
self.stage(path)
self.assertIn("rust:lint", self.selected())
self.assertNotIn("pre-commit:full", self.selected())

def test_mixed_python_and_markdown_selects_union(self):
self.stage("tasks/scripts/example.py")
self.stage("docs/example.mdx")
self.assertEqual(
self.selected(),
{
"license:check",
"python:format",
"python:format:check",
"python:lint",
"markdown:format",
"markdown:lint",
},
)

def test_chart_readme_also_requires_helm_checks(self):
self.stage("deploy/helm/openshell/README.md")
self.assertEqual(
self.selected(),
{
"license:check",
"helm:lint",
"helm:docs:check",
"markdown:format",
"markdown:lint",
},
)

def test_chart_template_selects_helm_checks(self):
self.stage("deploy/helm/openshell/templates/deployment.yaml")
self.assertEqual(
self.selected(),
{
"license:check",
"helm:lint",
"helm:docs:check",
},
)

def test_proto_selects_generated_code_consumers(self):
self.stage("proto/openshell.proto")
self.assertEqual(
self.selected(),
{
"license:check",
"proto:lint",
"rust:format",
"rust:format:check",
"rust:lockfiles:check",
"rust:lint",
"python:format",
"python:format:check",
"python:lint",
},
)

def test_shared_and_unknown_inputs_fall_back_to_full(self):
for path in (
"tasks/ci.toml",
"mise.toml",
"rust-toolchain.toml",
".cargo/config.toml",
"pyproject.toml",
".markdownlint-cli2.jsonc",
"tasks/scripts/pre_commit.py",
"scripts/update_license_headers.py",
"tasks/scripts/check_cargo_lockfile_alignment.py",
"scripts/lint-mermaid/lint-mermaid.mjs",
"buf.yaml",
"unknown.xyz",
):
with self.subTest(path=path):
self.git("read-tree", "--empty")
self.stage(path)
self.assertEqual(self.selected(), {"pre-commit:full"})

def test_rename_considers_old_and_new_paths(self):
self.stage("old.rs")
self.commit()
self.git("mv", "old.rs", "new.md")
self.assertIn("rust:lint", self.selected())
self.assertIn("markdown:lint", self.selected())

def test_deleted_file_still_selects_its_area(self):
self.stage("deleted.rs")
self.commit()
self.git("rm", "deleted.rs")
self.assertIn("rust:lint", self.selected())

def test_unstaged_changes_do_not_select_checks(self):
self.stage("README.md")
(self.root / "unstaged.rs").write_text("example\n")
self.assertEqual(self.selected(), {"markdown:format", "markdown:lint"})

def test_empty_index_runs_no_checks(self):
result = self.run_selector()
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn("No staged changes", result.stdout)

def test_full_override_even_with_empty_index(self):
self.assertEqual(self.selected("--full"), {"pre-commit:full"})

def test_git_failure_does_not_silently_skip_checks(self):
self.env["GIT_INDEX_FILE"] = str(self.root / "bad-index")
(self.root / "bad-index").write_text("not a Git index")
result = self.run_selector("--dry-run")
self.assertNotEqual(result.returncode, 0)
self.assertIn("index", result.stderr)

@unittest.skipUnless(shutil.which("mise"), "mise is required for task execution")
def test_selected_tasks_execute_through_mise_and_failures_propagate(self):
self.stage("README.md")
self.env["MISE_TRUSTED_CONFIG_PATHS"] = str(self.root)
config = self.root / "mise.toml"
config.write_text("""
[tasks."markdown:format"]
run = "git config --file format-ran fixture.ran yes"
[tasks."markdown:lint"]
run = "git config --file lint-ran fixture.ran yes"
""")
result = self.run_selector()
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(
self.git("config", "--file", "format-ran", "fixture.ran").stdout,
b"yes\n",
)
self.assertEqual(
self.git("config", "--file", "lint-ran", "fixture.ran").stdout,
b"yes\n",
)

config.write_text("""
[tasks."markdown:format"]
run = "git config --file format-ran fixture.ran yes"
[tasks."markdown:lint"]
run = "exit 7"
""")
result = self.run_selector()
self.assertNotEqual(result.returncode, 0)


if __name__ == "__main__":
unittest.main()
Loading
Loading