Skip to content
Merged
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
33 changes: 33 additions & 0 deletions kits/profile-dev-kit/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -456,6 +456,39 @@ Run the workflow from the repository root, for example:
beddel run -i ... workflows/plan-story.yaml
```

## Delivery: hook policy and proof (Story 8.2)

The plan, implement and verify-and-fix stages use tracked policies at
`policies/plan.json`, `policies/implement.json` and
`policies/verify-and-fix.json`. Each policy denies shell `git push` and `gh pr
merge` before allowing the other declared shell, read and write classes. The
policy copy and `hook.jsonl` live in one fresh 0700 run directory under
`~/.local/state/beddel/kiro-hook/runs/`; the policy digest is recorded in the
Stage outcome.

Immediately before each Coding-agent call, the stage writes
`~/.local/state/beddel/kiro-hook/pointers/<sha256(realpath(cwd))>.json` with
absolute `policy`, `log_path` and `stage` values. The pointer is created with
`O_CREAT|O_EXCL|O_NOFOLLOW` and mode 0600, and nothing is passed through the
agent environment. An existing pointer refuses the call. The pointer is
removed only when its bytes still match what the stage wrote. A pointer left by
a killed run is stale and the operator must remove it before retrying.

Stage refs contain these flat hook keys: `hook_log_sha256`, `hook_events`,
`hook_pre`, `hook_post`, `hook_denied`, `hook_stop`, `hook_errors`,
`hook_policy_sha256` and `kiro_session`. The Stage outcome accepts up to 32 refs,
so the existing stage refs and these nine flat keys remain in the unchanged
`profile-dev/stage-outcome/1` record schema. With N agent calls, the stage succeeds
only when `hook_stop == N` and `hook_errors == 0`; missing or unreadable proof
uses `hooks.missing`, and malformed or error events use `hooks.errors`. With no
agent calls all nine keys are `null`. Hook policies, pointers and logs stay
outside the records root and are not Evidence, Findings, Verdicts or Approval
inputs.

The hook wrapper does not normalize shell wrappers or grammar variants beyond
the agent-kit hook's existing rules. The installed agent must use the default
pointer directory. Review gets no pointer or hook proof (D-37).

## Delivery: implement stage

`implement-story` takes `repo_path`, `story_key`, `spec_path`, `branch` and
Expand Down
24 changes: 24 additions & 0 deletions kits/profile-dev-kit/kit.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,22 @@ tools:
target: "beddel_profile_dev.tools.stage_outcome:profile_record_stage_outcome"
description: "Append one create-only Stage outcome record outside the repository"
category: profile
- name: profile_hook_open
target: "beddel_profile_dev.tools.hook:profile_hook_open"
description: "Open a private per-stage hook run and copy its tracked policy"
category: profile
- name: profile_hook_arm
target: "beddel_profile_dev.tools.hook:profile_hook_arm"
description: "Arm the exclusive Kiro hook pointer for the repository cwd"
category: profile
- name: profile_hook_disarm
target: "beddel_profile_dev.tools.hook:profile_hook_disarm"
description: "Remove an unchanged Kiro hook pointer after an agent call"
category: profile
- name: profile_hook_proof
target: "beddel_profile_dev.tools.hook:profile_hook_proof"
description: "Merge hook counts and proof gates into a Stage outcome"
category: profile
- name: profile_implement_prepare
target: "beddel_profile_dev.tools.implement:profile_implement_prepare"
description: "Prepare one implementation unit on a feature branch"
Expand Down Expand Up @@ -231,6 +247,14 @@ targets:
target: "beddel_profile_dev.tools.plan:profile_plan_settle"
- name: profile_record_stage_outcome
target: "beddel_profile_dev.tools.stage_outcome:profile_record_stage_outcome"
- name: profile_hook_open
target: "beddel_profile_dev.tools.hook:profile_hook_open"
- name: profile_hook_arm
target: "beddel_profile_dev.tools.hook:profile_hook_arm"
- name: profile_hook_disarm
target: "beddel_profile_dev.tools.hook:profile_hook_disarm"
- name: profile_hook_proof
target: "beddel_profile_dev.tools.hook:profile_hook_proof"
- name: profile_implement_prepare
target: "beddel_profile_dev.tools.implement:profile_implement_prepare"
- name: profile_implement_settle
Expand Down
1 change: 1 addition & 0 deletions kits/profile-dev-kit/policies/implement.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"schema":"beddel.kiro-hook-policy/1","rules":[{"id":"shell.git-push","effect":"deny","tool_class":"shell","argv_prefix":["git","push"]},{"id":"shell.gh-pr-merge","effect":"deny","tool_class":"shell","argv_prefix":["gh","pr","merge"]},{"id":"shell.any","effect":"allow","tool_class":"shell"},{"id":"read.any","effect":"allow","tool_class":"read"},{"id":"write.any","effect":"allow","tool_class":"write"}]}
1 change: 1 addition & 0 deletions kits/profile-dev-kit/policies/plan.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"schema":"beddel.kiro-hook-policy/1","rules":[{"id":"shell.git-push","effect":"deny","tool_class":"shell","argv_prefix":["git","push"]},{"id":"shell.gh-pr-merge","effect":"deny","tool_class":"shell","argv_prefix":["gh","pr","merge"]},{"id":"shell.any","effect":"allow","tool_class":"shell"},{"id":"read.any","effect":"allow","tool_class":"read"},{"id":"write.any","effect":"allow","tool_class":"write"}]}
1 change: 1 addition & 0 deletions kits/profile-dev-kit/policies/verify-and-fix.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"schema":"beddel.kiro-hook-policy/1","rules":[{"id":"shell.git-push","effect":"deny","tool_class":"shell","argv_prefix":["git","push"]},{"id":"shell.gh-pr-merge","effect":"deny","tool_class":"shell","argv_prefix":["gh","pr","merge"]},{"id":"shell.any","effect":"allow","tool_class":"shell"},{"id":"read.any","effect":"allow","tool_class":"read"},{"id":"write.any","effect":"allow","tool_class":"write"}]}
163 changes: 163 additions & 0 deletions kits/profile-dev-kit/python/beddel_profile_dev/hook_proof.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
# fmt: off
from __future__ import annotations

import hashlib
import json
import os
import re
import secrets
import stat
from collections.abc import Mapping
from datetime import UTC, datetime
from pathlib import Path
from typing import Any

from beddel_profile_dev.config import get_kit_root

HOOK_KEYS = ("hook_log_sha256", "hook_events", "hook_pre", "hook_post", "hook_denied", "hook_stop", "hook_errors", "hook_policy_sha256", "kiro_session")
_STAGE_RE = re.compile(r"[a-z][a-z0-9-]{0,31}")
_SESSION_RE = re.compile(r"[A-Za-z0-9._-]{1,128}")
_MAX_LOG_BYTES = 8 * 1024 * 1024
_HOOK_SCHEMA = "beddel.kiro-hook/1"


def pointers_dir() -> Path:
return Path.home() / ".local/state/beddel/kiro-hook/pointers"


def runs_dir() -> Path:
return Path.home() / ".local/state/beddel/kiro-hook/runs"


def pointer_path(cwd: str | os.PathLike[str]) -> Path:
digest = hashlib.sha256(os.path.realpath(os.fspath(cwd)).encode()).hexdigest()
return pointers_dir() / f"{digest}.json"


def policy_path(stage: str) -> Path:
return get_kit_root() / "policies" / f"{stage}.json"


def _private_directory(path: Path) -> bool:
try:
if path.is_symlink(): return False
if not path.exists(): path.mkdir(parents=True, mode=0o700)
info = path.stat()
return stat.S_ISDIR(info.st_mode) and info.st_uid == os.getuid() and not info.st_mode & 0o077
except OSError: return False


def _secure_regular(path: Path, *, maximum: int | None = None) -> bool:
try:
info = path.lstat()
return stat.S_ISREG(info.st_mode) and info.st_uid == os.getuid() and not info.st_mode & 0o077 and (maximum is None or info.st_size <= maximum)
except OSError: return False


def _write_exclusive(path: Path, data: bytes, mode: int) -> None:
flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0)
fd = os.open(path, flags, mode)
try:
remaining = data
while remaining: remaining = remaining[os.write(fd, remaining):]
os.fchmod(fd, mode)
os.fsync(fd)
except BaseException:
try: path.unlink()
except OSError: pass
raise
finally: os.close(fd)


def open_run(stage: str) -> dict[str, Any]:
if not isinstance(stage, str) or _STAGE_RE.fullmatch(stage) is None: return {"ok": False, "reason": "hooks.unavailable"}
source = policy_path(stage)
try:
if source.is_symlink() or not source.is_file(): return {"ok": False, "reason": "hooks.unavailable"}
policy = source.read_bytes()
root = runs_dir()
if not _private_directory(root): return {"ok": False, "reason": "hooks.unavailable"}
run = root / f"{stage}-{datetime.now(UTC).strftime('%Y%m%dT%H%M%S%fZ')}-{secrets.token_hex(8)}"
try: os.mkdir(run, 0o700)
except FileExistsError: return {"ok": False, "reason": "hooks.unavailable"}
policy_copy, log_path = run / "policy.json", run / "hook.jsonl"
try: _write_exclusive(policy_copy, policy, 0o600)
except OSError:
try: policy_copy.unlink(missing_ok=True); run.rmdir()
except OSError: pass
return {"ok": False, "reason": "hooks.unavailable"}
return {"ok": True, "stage": stage, "run": str(run), "log_path": str(log_path), "policy_path": str(policy_copy), "policy_sha256": hashlib.sha256(policy).hexdigest()}
except (OSError, ValueError): return {"ok": False, "reason": "hooks.unavailable"}


def _repo_cwd(repo_path: str) -> Path | None:
try:
repo, cwd = Path(os.path.realpath(repo_path)), Path(os.path.realpath(os.getcwd()))
return repo if repo.is_dir() and cwd == repo else None
except (OSError, TypeError, ValueError): return None


def write_pointer(repo_path: str, stage: str, hook: Mapping[str, Any]) -> dict[str, Any]:
repo = _repo_cwd(repo_path)
result = {"armed": False, "reason": "hooks.unavailable", "stage": stage, "log_path": hook.get("log_path") if isinstance(hook, Mapping) else None, "pointer_sha256": None}
if repo is None or not isinstance(hook, Mapping) or hook.get("ok") is not True: return result
log_path, policy = hook.get("log_path"), hook.get("policy_path")
if not isinstance(log_path, str) or not isinstance(policy, str) or not Path(log_path).is_absolute() or not Path(policy).is_absolute() or hook.get("stage") != stage or not _secure_regular(Path(policy)): return result
if not _private_directory(pointers_dir()): return result
pointer = pointer_path(repo)
raw = json.dumps({"log_path": log_path, "policy": policy, "stage": stage}, sort_keys=True, separators=(",", ":")).encode()
try: _write_exclusive(pointer, raw, 0o600)
except FileExistsError:
result["reason"] = "hooks.pointer_exists"
return result
except OSError: return result
result.update(armed=True, reason=None, pointer_sha256=hashlib.sha256(raw).hexdigest())
return result


def remove_pointer(repo_path: str, armed: Mapping[str, Any] | None) -> dict[str, bool]:
if not isinstance(armed, Mapping) or armed.get("armed") is not True: return {"removed": False}
expected, repo = armed.get("pointer_sha256"), _repo_cwd(repo_path)
if repo is None or not isinstance(expected, str): return {"removed": False}
pointer = pointer_path(repo)
try:
if not _secure_regular(pointer) or hashlib.sha256(pointer.read_bytes()).hexdigest() != expected: return {"removed": False}
pointer.unlink()
return {"removed": True}
except OSError: return {"removed": False}


def null_keys() -> dict[str, None]: return {key: None for key in HOOK_KEYS}


def count_log(log_path: str | os.PathLike[str], policy_sha256: str | None = None) -> dict[str, Any] | None:
path = Path(log_path)
if not _secure_regular(path, maximum=_MAX_LOG_BYTES): return None
try: raw = path.read_bytes()
except OSError: return None
result: dict[str, Any] = null_keys()
result.update({"hook_log_sha256": hashlib.sha256(raw).hexdigest(), "hook_events": 0, "hook_pre": 0, "hook_post": 0, "hook_denied": 0, "hook_stop": 0, "hook_errors": 0})
sessions: list[str] = []
for line in raw.splitlines():
if not line.strip(): continue
result["hook_events"] += 1
try: record = json.loads(line)
except (json.JSONDecodeError, UnicodeDecodeError, TypeError, RecursionError, ValueError):
result["hook_errors"] += 1
continue
if not isinstance(record, dict) or record.get("v") != _HOOK_SCHEMA:
result["hook_errors"] += 1
continue
event, digest = record.get("event"), record.get("policy_sha256")
if event in {"pre", "post", "stop"}: result[f"hook_{event}"] += 1
if record.get("decision") == "deny": result["hook_denied"] += 1
if record.get("decision") == "error": result["hook_errors"] += 1
if policy_sha256 is not None and digest != policy_sha256: result["hook_errors"] += 1
if result["hook_policy_sha256"] is None and isinstance(digest, str): result["hook_policy_sha256"] = digest
session = record.get("session_id")
if isinstance(session, str) and _SESSION_RE.fullmatch(session):
joined = ",".join([*sessions, session])
if session not in sessions and len(joined) <= 512: sessions.append(session)
result["kiro_session"] = ",".join(sessions) if sessions else None
return result
# fmt: on
150 changes: 150 additions & 0 deletions kits/profile-dev-kit/python/beddel_profile_dev/tools/hook.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
from __future__ import annotations

from collections.abc import Mapping
from typing import Any

from beddel.tools import beddel_tool

from beddel_profile_dev._errors import PROFILE_STAGE_OUTCOME_REFUSED, ProfileError
from beddel_profile_dev.hook_proof import (
count_log,
null_keys,
open_run,
remove_pointer,
write_pointer,
)


def _runtime_failure(stage: str | None = None) -> dict[str, Any]:
result: dict[str, Any] = {"ok": False, "reason": "hooks.unavailable"}
if stage is not None:
result["stage"] = stage
return result


@beddel_tool(
name="profile_hook_open",
description="Open one private per-stage hook run and copy its tracked policy",
category="profile",
)
def profile_hook_open(stage: str) -> dict[str, Any]:
try:
return open_run(stage)
except Exception: # noqa: BLE001
return _runtime_failure(stage)


@beddel_tool(
name="profile_hook_arm",
description="Arm the exclusive Kiro hook pointer for the repository cwd",
category="profile",
)
def profile_hook_arm(
repo_path: str, stage: str, hook: Mapping[str, Any] | None
) -> dict[str, Any]:
try:
if not isinstance(hook, Mapping):
return {
"armed": False,
"reason": "hooks.unavailable",
"stage": stage,
"log_path": None,
"pointer_sha256": None,
}
return write_pointer(repo_path, stage, hook)
except Exception: # noqa: BLE001
return {
"armed": False,
"reason": "hooks.unavailable",
"stage": stage,
"log_path": hook.get("log_path") if isinstance(hook, Mapping) else None,
"pointer_sha256": None,
}


@beddel_tool(
name="profile_hook_disarm",
description="Remove a Kiro hook pointer only when its bytes are unchanged",
category="profile",
)
def profile_hook_disarm(
repo_path: str, armed: Mapping[str, Any] | None
) -> dict[str, bool]:
try:
return remove_pointer(repo_path, armed)
except Exception: # noqa: BLE001
return {"removed": False}


@beddel_tool(
name="profile_hook_proof",
description="Merge hook counts and proof gates into a Stage outcome",
category="profile",
)
def profile_hook_proof(
stage: str,
hook: Mapping[str, Any] | None,
calls: list[Mapping[str, Any] | None] | None,
settled: Mapping[str, Any] | None,
) -> dict[str, Any]:
if not isinstance(settled, Mapping):
raise ProfileError(
PROFILE_STAGE_OUTCOME_REFUSED,
"stage outcome refused",
{"reason": "settled.invalid"},
)
refs = settled.get("refs")
base_refs = dict(refs) if isinstance(refs, Mapping) else {}
entries = calls if isinstance(calls, list) else ([] if calls is None else [calls])
armed_entries = [
item
for item in entries
if isinstance(item, Mapping) and item.get("armed") is True
]
n_calls = len(armed_entries)
hook_keys = null_keys()

refusal = next(
(
item.get("reason") or "hooks.unavailable"
for item in entries
if isinstance(item, Mapping) and item.get("armed") is not True
),
None,
)
if refusal is not None:
return {
"stage": stage,
"story_key": settled.get("story_key"),
"outcome": "failed",
"reason": refusal if isinstance(refusal, str) else "hooks.unavailable",
"refs": {**base_refs, **hook_keys},
}
if n_calls == 0:
return {
"stage": stage,
"story_key": settled.get("story_key"),
"outcome": settled.get("outcome"),
"reason": settled.get("reason"),
"refs": {**base_refs, **hook_keys},
}

log_path = hook.get("log_path") if isinstance(hook, Mapping) else None
policy_digest = hook.get("policy_sha256") if isinstance(hook, Mapping) else None
counts = count_log(log_path, policy_digest) if isinstance(log_path, str) else None
if counts is None:
reason: str | None = "hooks.missing"
else:
hook_keys = counts
reason = (
"hooks.missing"
if counts["hook_stop"] != n_calls
else ("hooks.errors" if counts["hook_errors"] > 0 else None)
)
return {
"stage": stage,
"story_key": settled.get("story_key"),
"outcome": "failed" if reason is not None else settled.get("outcome"),
"reason": reason if reason is not None else settled.get("reason"),
"refs": {**base_refs, **hook_keys},
}
Loading
Loading