Repository navigation
Retain pinned hook bundles across plugin cache updates #106
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
adit-chandra
wants to merge
3
commits into
main
Choose a base branch
from
adit-chandra/codex/retained-hook-bundles
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| """Describe the complete portable hook bundle pinned by a generated command.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import hashlib | ||
| import json | ||
| from pathlib import Path | ||
|
|
||
| from promptless_instruction_hub.fs import JsonValue | ||
| from promptless_instruction_hub.hook_launcher import RUNNER_NAME | ||
| from promptless_instruction_hub.models import Harness, LoadedAsset | ||
|
|
||
|
|
||
| def write_bundle_manifest(hook_root: Path, asset: LoadedAsset, target: Harness) -> str: | ||
| spec = asset.metadata.hook | ||
| assert spec is not None | ||
| paths = [hook_root / RUNNER_NAME, *(path for path in (hook_root / asset.id).rglob("*") if path.is_file())] | ||
| files: dict[str, JsonValue] = { | ||
| path.relative_to(hook_root).as_posix(): { | ||
| "sha256": hashlib.sha256(path.read_bytes()).hexdigest(), | ||
| "executable": bool(path.stat().st_mode & 0o111), | ||
| } | ||
| for path in sorted(paths) | ||
| } | ||
| manifest = { | ||
| "schema": 1, | ||
| "host": target, | ||
| "hook": asset.id, | ||
| "entrypoint": f"{asset.id}/{spec.entrypoint}", | ||
| "config": spec.model_dump(mode="json"), | ||
| "files": files, | ||
| } | ||
| payload = json.dumps(manifest, sort_keys=True, separators=(",", ":")).encode() | ||
| digest = hashlib.sha256(payload).hexdigest() | ||
| path = hook_root / "_bundles" / f"{digest}.json" | ||
| path.parent.mkdir(parents=True, exist_ok=True) | ||
| path.write_bytes(payload) | ||
| return digest | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,152 @@ | ||
| """Python 3.9+ launcher embedded in hook commands, independent of plugin files. | ||
|
|
||
| Portable hooks provide context, not policy decisions. Isolate their failures | ||
| here so Python's missing-script exit code 2 cannot become a native hook veto. | ||
| Keep this module standard-library-only and preserve in-process signal delivery. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import errno | ||
| import hashlib | ||
| import json | ||
| import os | ||
| from pathlib import Path, PurePosixPath | ||
| import runpy | ||
| import stat | ||
| import sys | ||
| import tempfile | ||
|
|
||
| RUNNER_NAME = "_instruction_hub_hook.py" | ||
|
|
||
|
|
||
| def data_root() -> Path: | ||
| """Use a host-independent location that plugin cache cleanup does not own.""" | ||
| override = os.environ.get("PROMPTLESS_HOOK_DATA_HOME") | ||
| if override: | ||
| return Path(override).expanduser() / "v1" | ||
| base = Path(os.environ.get("XDG_DATA_HOME") or Path.home() / ".local/share") | ||
| return base / "promptless/hook-runtime/v1" | ||
|
|
||
|
|
||
| def read_manifest(path: Path, digest: str) -> tuple[bytes, dict]: | ||
| payload = path.read_bytes() | ||
| if hashlib.sha256(payload).hexdigest() != digest: | ||
| raise ValueError("hook manifest digest mismatch") | ||
| manifest = json.loads(payload) | ||
| if manifest["schema"] != 1 or manifest["host"] not in {"claude", "codex", "cursor"}: | ||
| raise ValueError("unsupported hook bundle") | ||
| files = manifest["files"] | ||
| if RUNNER_NAME not in files or manifest["entrypoint"] not in files: | ||
| raise ValueError("incomplete hook manifest") | ||
| for name in files: | ||
| path_name = PurePosixPath(name) | ||
| if path_name.is_absolute() or ".." in path_name.parts or "\\" in name or name != path_name.as_posix(): | ||
| raise ValueError("invalid hook bundle path") | ||
| return payload, manifest | ||
|
|
||
|
|
||
| def checked_file(root: Path, name: str, expected: dict) -> bytes: | ||
| path = root / name | ||
| # Source assets reject symlinks at build time. Check installed bundles too, | ||
| # including parent directories, before copying or executing their contents. | ||
| current = root | ||
| for part in ("", *PurePosixPath(name).parts): | ||
| current = current / part | ||
| if current.is_symlink(): | ||
| raise ValueError("symlink in hook bundle") | ||
| if not stat.S_ISREG(path.stat().st_mode): | ||
| raise ValueError("non-regular file in hook bundle") | ||
| payload = path.read_bytes() | ||
| if hashlib.sha256(payload).hexdigest() != expected["sha256"]: | ||
| raise ValueError(f"hook file digest mismatch: {name}") | ||
| return payload | ||
|
|
||
|
|
||
| def retained_bundle(source: Path, digest: str) -> tuple[Path, dict]: | ||
| """Publish a complete immutable bundle; never resolve to a newer version.""" | ||
| if len(digest) != 64 or any(c not in "0123456789abcdef" for c in digest): | ||
| raise ValueError("invalid hook bundle digest") | ||
| bundles = data_root() / "bundles" | ||
| destination = bundles / digest | ||
| if not destination.exists(): | ||
| payload, manifest = read_manifest(source / "_bundles" / f"{digest}.json", digest) | ||
| bundles.mkdir(parents=True, exist_ok=True, mode=0o700) | ||
| with tempfile.TemporaryDirectory(prefix=".staging-", dir=bundles) as temporary: | ||
| staging = Path(temporary) / "bundle" | ||
| staging.mkdir(mode=0o700) | ||
| for name, expected in manifest["files"].items(): | ||
| content = checked_file(source, name, expected) | ||
| target = staging / name | ||
| target.parent.mkdir(parents=True, exist_ok=True) | ||
| target.write_bytes(content) | ||
| target.chmod(0o700 if expected["executable"] else 0o600) | ||
| (staging / "manifest.json").write_bytes(payload) | ||
| try: | ||
| staging.rename(destination) | ||
| except OSError as exc: | ||
| # Another hook may have published the same digest while we | ||
| # staged. It is safe to use only after validating that winner. | ||
| if exc.errno not in {errno.EEXIST, errno.ENOTEMPTY}: | ||
| raise | ||
| _, manifest = read_manifest(destination / "manifest.json", digest) | ||
| expected_paths = set(manifest["files"]) | {"manifest.json"} | ||
| for path in destination.rglob("*"): | ||
| if path.is_symlink() or path.is_file() and path.relative_to(destination).as_posix() not in expected_paths: | ||
| raise ValueError("unexpected file in retained hook bundle") | ||
| for name, expected in manifest["files"].items(): | ||
| checked_file(destination, name, expected) | ||
| return destination, manifest | ||
|
|
||
|
|
||
| def report_unavailable(digest: str, exc: Exception) -> None: | ||
| """Warn once per unavailable bundle; do not persist hook input or output.""" | ||
| try: | ||
| warnings = data_root() / "warnings" | ||
| warnings.mkdir(parents=True, exist_ok=True, mode=0o700) | ||
| # Hash even malformed digests before using them as a filesystem key. | ||
| key = hashlib.sha256(digest.encode()).hexdigest() | ||
| with (warnings / key).open("x"): | ||
| pass | ||
| except FileExistsError: | ||
| return | ||
| except OSError: | ||
| # An unwritable data directory must remain visible and nonblocking. | ||
| pass | ||
| detail = str(exc).replace("\n", " ")[:500] | ||
| print(f"Instruction Hub context hook skipped: {type(exc).__name__}: {detail}", file=sys.stderr) | ||
|
|
||
|
|
||
| def main() -> None: | ||
| sys.dont_write_bytecode = True | ||
| source, digest, *options = sys.argv[1:] | ||
| try: | ||
| root, manifest = retained_bundle(Path(source), digest) | ||
| except Exception as exc: | ||
| # Cache removal, incomplete installs, and corrupt/unwritable storage | ||
| # must never turn this context hook into a host policy decision. | ||
| report_unavailable(digest, exc) | ||
| return | ||
| try: | ||
| key = hashlib.sha256(digest.encode()).hexdigest() | ||
| (data_root() / "warnings" / key).unlink(missing_ok=True) | ||
| except OSError: | ||
| pass # Diagnostic bookkeeping cannot prevent an otherwise healthy hook. | ||
| if options == ["--prepare"]: | ||
| return | ||
| runner = str(root / RUNNER_NAME) | ||
| sys.argv = [runner, "--host", manifest["host"], "--entrypoint", str(root / manifest["entrypoint"])] | ||
| try: | ||
| runpy.run_path(runner, run_name="__main__") | ||
| except SystemExit as exc: | ||
| if exc.code not in (None, 0): | ||
| print(f"Instruction Hub context hook skipped: adapter exited {exc.code!s:.100}.", file=sys.stderr) | ||
| except Exception as exc: | ||
| # This is the boundary for arbitrary authored Python, including import | ||
| # failures while an updater removes a bundle. Never swallow cancellation. | ||
| detail = str(exc).replace("\n", " ")[:500] | ||
| print(f"Instruction Hub context hook skipped: {type(exc).__name__}: {detail}", file=sys.stderr) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[Medium] Normalize the entrypoint before storing it in the manifest. HookDefinition accepts paths such as
./handler.pyandsub//handler.py, which previously executed successfully, but the manifest file keys are normalized by pathlib while this field preserves the original spelling. Consequently, read_manifest rejects these valid bundles as "incomplete hook manifest", and both preparation and ordinary invocations silently skip the hook on all targets. Construct this field with(Path(asset.id) / spec.entrypoint).as_posix()and add coverage for these accepted spellings.