unrig 0.1.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.
- unrig/__init__.py +4 -0
- unrig/cli.py +221 -0
- unrig/cli_core.py +441 -0
- unrig/config.py +445 -0
- unrig/diff_counter.py +1617 -0
- unrig/format_registry.py +732 -0
- unrig/junit_verifier.py +335 -0
- unrig/l0_guard.py +391 -0
- unrig/replay.py +326 -0
- unrig/templates/PROTOCOL.md +25 -0
- unrig/templates/blind_auditor_prompt.md +32 -0
- unrig/templates/unrig.yaml +47 -0
- unrig-0.1.0.dist-info/METADATA +192 -0
- unrig-0.1.0.dist-info/RECORD +18 -0
- unrig-0.1.0.dist-info/WHEEL +5 -0
- unrig-0.1.0.dist-info/entry_points.txt +2 -0
- unrig-0.1.0.dist-info/licenses/LICENSE +194 -0
- unrig-0.1.0.dist-info/top_level.txt +1 -0
unrig/__init__.py
ADDED
unrig/cli.py
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
"""Unrig CLI entrypoint (`init`, `hook`, `verify`, `replay`, `ratchet`, `stats`)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
import sys
|
|
8
|
+
from typing import TextIO
|
|
9
|
+
|
|
10
|
+
from . import __version__
|
|
11
|
+
from .cli_core import (
|
|
12
|
+
clear_intercept_stats,
|
|
13
|
+
handle_hook_invocation,
|
|
14
|
+
init_workspace,
|
|
15
|
+
read_intercept_stats,
|
|
16
|
+
verify_workspace,
|
|
17
|
+
)
|
|
18
|
+
from .config import UnrigConfigError, load_config
|
|
19
|
+
from .diff_counter import find_ratchet_slack, prune_ratchet
|
|
20
|
+
from .replay import run_builtin_replay_suite
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _resolve_root(raw_root: str | None) -> Path:
|
|
24
|
+
return Path(raw_root).resolve() if raw_root else Path.cwd().resolve()
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _out_line(text: str, *, err: bool = False) -> None:
|
|
28
|
+
_write_utf8_stream(sys.stderr if err else sys.stdout, text + "\n")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _cmd_init(args: argparse.Namespace) -> int:
|
|
32
|
+
root = _resolve_root(args.root)
|
|
33
|
+
results = init_workspace(root, force=args.force, client=args.client)
|
|
34
|
+
_out_line(f"Unrig v{__version__} initialized in: {root}")
|
|
35
|
+
for rel, status in results:
|
|
36
|
+
_out_line(f" - {rel}: {status}")
|
|
37
|
+
_out_line("Next step: commit `.unrig.yaml` and `.unrig/` to lock L0 integrity in git.")
|
|
38
|
+
return 0
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _read_utf8_stdin() -> str:
|
|
42
|
+
"""Read hook JSON payload from stdin using UTF-8 regardless of Windows console codepage."""
|
|
43
|
+
buf = getattr(sys.stdin, "buffer", None)
|
|
44
|
+
if buf is not None:
|
|
45
|
+
return buf.read().decode("utf-8", errors="replace")
|
|
46
|
+
return sys.stdin.read()
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _write_utf8_stream(stream: TextIO, text: str) -> None:
|
|
50
|
+
"""Write text to stdout/stderr as UTF-8 so non-ASCII hook responses never raise cp936 encode errors."""
|
|
51
|
+
if not text:
|
|
52
|
+
return
|
|
53
|
+
buf = getattr(stream, "buffer", None)
|
|
54
|
+
if buf is not None:
|
|
55
|
+
buf.write(text.encode("utf-8", errors="replace"))
|
|
56
|
+
buf.flush()
|
|
57
|
+
else:
|
|
58
|
+
stream.write(text)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _cmd_hook(args: argparse.Namespace) -> int:
|
|
62
|
+
payload = _read_utf8_stdin()
|
|
63
|
+
code, stdout_text, stderr_text = handle_hook_invocation(
|
|
64
|
+
payload,
|
|
65
|
+
explicit_root=args.root,
|
|
66
|
+
explicit_client=args.client,
|
|
67
|
+
)
|
|
68
|
+
_write_utf8_stream(sys.stdout, stdout_text)
|
|
69
|
+
_write_utf8_stream(sys.stderr, stderr_text)
|
|
70
|
+
return code
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _cmd_verify(args: argparse.Namespace) -> int:
|
|
74
|
+
root = _resolve_root(args.root)
|
|
75
|
+
cfg_path = Path(args.config).resolve() if args.config else None
|
|
76
|
+
passed, lines = verify_workspace(
|
|
77
|
+
root,
|
|
78
|
+
config_path=cfg_path,
|
|
79
|
+
baseline=args.baseline,
|
|
80
|
+
strict_l0=args.strict_l0,
|
|
81
|
+
)
|
|
82
|
+
for ln in lines:
|
|
83
|
+
_out_line(ln)
|
|
84
|
+
return 0 if passed else 1
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _cmd_replay(args: argparse.Namespace) -> int:
|
|
88
|
+
results = run_builtin_replay_suite()
|
|
89
|
+
failed = 0
|
|
90
|
+
_out_line(f"Unrig v{__version__} Referee Escape-Replay Suite ({len(results)} scenarios):")
|
|
91
|
+
for r in results:
|
|
92
|
+
tag = "[PASS]" if r.passed else "[FAIL]"
|
|
93
|
+
_out_line(f" {tag} {r.case_id}: {r.description} -> {r.detail}")
|
|
94
|
+
if not r.passed:
|
|
95
|
+
failed += 1
|
|
96
|
+
return 0 if failed == 0 else 1
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _cmd_ratchet(args: argparse.Namespace) -> int:
|
|
100
|
+
root = _resolve_root(args.root)
|
|
101
|
+
try:
|
|
102
|
+
config = load_config(root)
|
|
103
|
+
except UnrigConfigError as exc:
|
|
104
|
+
_out_line(f"[FAIL] [CONFIG_ERROR] {exc}", err=True)
|
|
105
|
+
return 1
|
|
106
|
+
|
|
107
|
+
if args.prune:
|
|
108
|
+
slacks, errors = prune_ratchet(root, config, dry_run=False)
|
|
109
|
+
if errors:
|
|
110
|
+
for err in errors:
|
|
111
|
+
_out_line(f"[FAIL] {err}", err=True)
|
|
112
|
+
return 1
|
|
113
|
+
if not slacks:
|
|
114
|
+
_out_line("[PASS] Ratchet ledger already tight (0 entries pruned).")
|
|
115
|
+
return 0
|
|
116
|
+
for s in slacks:
|
|
117
|
+
action = "removed (0 remaining)" if s.actual_count == 0 else f"tightened {s.entry.count} -> {s.actual_count}"
|
|
118
|
+
_out_line(f" - {s.entry.file} ({s.entry.rule}): {action}")
|
|
119
|
+
_out_line(f"[PASS] Pruned {len(slacks)} stale ratchet entry(ies) in '{config.ratchet_file}'.")
|
|
120
|
+
return 0
|
|
121
|
+
|
|
122
|
+
slacks, errors = find_ratchet_slack(root, config)
|
|
123
|
+
if errors:
|
|
124
|
+
for err in errors:
|
|
125
|
+
_out_line(f"[FAIL] {err}", err=True)
|
|
126
|
+
return 1
|
|
127
|
+
if slacks:
|
|
128
|
+
for s in slacks:
|
|
129
|
+
_out_line(
|
|
130
|
+
f"[RATCHET_SLACK] {s.entry.file} ({s.entry.rule}): "
|
|
131
|
+
f"cap={s.entry.count}, actual={s.actual_count}"
|
|
132
|
+
)
|
|
133
|
+
return 1
|
|
134
|
+
_out_line("[PASS] Ratchet ledger is tight (no stale slack).")
|
|
135
|
+
return 0
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _cmd_stats(args: argparse.Namespace) -> int:
|
|
139
|
+
root = _resolve_root(args.root)
|
|
140
|
+
if args.clear:
|
|
141
|
+
removed = clear_intercept_stats(root)
|
|
142
|
+
_out_line("[PASS] Cleared local interception log." if removed else "[PASS] No local interception log to clear.")
|
|
143
|
+
return 0
|
|
144
|
+
stats = read_intercept_stats(root, days=args.days)
|
|
145
|
+
scope = f"last {args.days} day(s)" if args.days is not None else "all time"
|
|
146
|
+
_out_line(f"Unrig Local Interception Ledger ({scope}) — {root}")
|
|
147
|
+
_out_line(f" Total intercepted: {stats['total']}")
|
|
148
|
+
if stats["total"] == 0:
|
|
149
|
+
_out_line(" (No blocked escapes recorded yet in `.unrig/.cache/events.jsonl`.)")
|
|
150
|
+
return 0
|
|
151
|
+
_out_line(f" By outcome: {stats['by_outcome']}")
|
|
152
|
+
_out_line(f" By rule/code: {stats['by_code']}")
|
|
153
|
+
_out_line(f" By client: {stats['by_client']}")
|
|
154
|
+
_out_line(" Recent interceptions:")
|
|
155
|
+
for ev in stats["recent"][-5:]:
|
|
156
|
+
_out_line(f" - [{ev.get('ts')}] {ev.get('client')}/{ev.get('event')} -> {ev.get('codes')} | {ev.get('detail')}")
|
|
157
|
+
return 0
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
161
|
+
parser = argparse.ArgumentParser(
|
|
162
|
+
prog="unrig",
|
|
163
|
+
description="Unrig — Anti-tamper gates, JUnit/diff verification, and isolated blind review for coding agents.",
|
|
164
|
+
)
|
|
165
|
+
parser.add_argument("--version", action="version", version=f"unrig {__version__}")
|
|
166
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
167
|
+
|
|
168
|
+
p_init = sub.add_parser("init", help="Initialize `.unrig.yaml` and `.unrig/` templates.")
|
|
169
|
+
p_init.add_argument("--root", default=None, help="Target repository root (default: cwd).")
|
|
170
|
+
p_init.add_argument("--force", action="store_true", help="Overwrite existing templates.")
|
|
171
|
+
p_init.add_argument(
|
|
172
|
+
"--client",
|
|
173
|
+
choices=["claude", "antigravity", "gemini", "all"],
|
|
174
|
+
default=None,
|
|
175
|
+
help="Also generate hook configuration for Claude Code, Google Antigravity, Gemini CLI, or all.",
|
|
176
|
+
)
|
|
177
|
+
p_init.set_defaults(func=_cmd_init)
|
|
178
|
+
|
|
179
|
+
p_hook = sub.add_parser("hook", help="PreToolUse / BeforeTool / Stop stdin hook guard.")
|
|
180
|
+
p_hook.add_argument("--root", default=None, help="Repository root (default: resolved from payload or cwd).")
|
|
181
|
+
p_hook.add_argument(
|
|
182
|
+
"--client",
|
|
183
|
+
choices=["auto", "claude", "antigravity", "gemini"],
|
|
184
|
+
default="auto",
|
|
185
|
+
help="Hook protocol adapter (default: auto-detect from stdin JSON).",
|
|
186
|
+
)
|
|
187
|
+
p_hook.set_defaults(func=_cmd_hook)
|
|
188
|
+
|
|
189
|
+
p_verify = sub.add_parser("verify", help="Verify L0 integrity, ratchet, diff counters, and JUnit freshness.")
|
|
190
|
+
p_verify.add_argument("--root", default=None, help="Repository root (default: cwd).")
|
|
191
|
+
p_verify.add_argument("--config", default=None, help="Optional explicit `.unrig.yaml` path.")
|
|
192
|
+
p_verify.add_argument("--baseline", default=None, help="Git revision baseline for diff comparison.")
|
|
193
|
+
p_verify.add_argument("--strict-l0", action="store_true", help="Fail if protected L0 files are untracked.")
|
|
194
|
+
p_verify.set_defaults(func=_cmd_verify)
|
|
195
|
+
|
|
196
|
+
p_replay = sub.add_parser("replay", help="Run built-in referee escape-replay and self-mutation tests.")
|
|
197
|
+
p_replay.set_defaults(func=_cmd_replay)
|
|
198
|
+
|
|
199
|
+
p_ratchet = sub.add_parser("ratchet", help="Inspect or prune stale `.unrig/ratchet.json` slack.")
|
|
200
|
+
p_ratchet.add_argument("--root", default=None, help="Repository root (default: cwd).")
|
|
201
|
+
p_ratchet.add_argument("--prune", action="store_true", help="Tighten stale ratchet caps in place (human maintenance).")
|
|
202
|
+
p_ratchet.add_argument("--check", action="store_true", help="Exit 1 if any ratchet entry has stale slack (default).")
|
|
203
|
+
p_ratchet.set_defaults(func=_cmd_ratchet)
|
|
204
|
+
|
|
205
|
+
p_stats = sub.add_parser("stats", help="Show local interception ledger summary from `.unrig/.cache/events.jsonl`.")
|
|
206
|
+
p_stats.add_argument("--root", default=None, help="Repository root (default: cwd).")
|
|
207
|
+
p_stats.add_argument("--days", type=int, default=None, help="Only include events from the last N days.")
|
|
208
|
+
p_stats.add_argument("--clear", action="store_true", help="Clear the local interception log.")
|
|
209
|
+
p_stats.set_defaults(func=_cmd_stats)
|
|
210
|
+
|
|
211
|
+
return parser
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def main(argv: list[str] | None = None) -> int:
|
|
215
|
+
parser = build_parser()
|
|
216
|
+
args = parser.parse_args(argv)
|
|
217
|
+
return int(args.func(args))
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
if __name__ == "__main__":
|
|
221
|
+
raise SystemExit(main())
|
unrig/cli_core.py
ADDED
|
@@ -0,0 +1,441 @@
|
|
|
1
|
+
"""Core workspace operations shared by `cli.py` and `replay.py`."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections import Counter
|
|
6
|
+
from datetime import datetime, timedelta, timezone
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
import re
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from .config import UnrigConfigError, load_config
|
|
14
|
+
from .diff_counter import find_ratchet_slack, verify_incremental_diff_with_stats
|
|
15
|
+
from .junit_verifier import verify_reports_and_artifacts
|
|
16
|
+
from .l0_guard import (
|
|
17
|
+
check_l0_integrity,
|
|
18
|
+
detect_hook_client,
|
|
19
|
+
evaluate_hook_payload,
|
|
20
|
+
format_hook_response,
|
|
21
|
+
resolve_hook_repo_root,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
_TEMPLATES_DIR = Path(__file__).resolve().parent / "templates"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _client_hook_files(client: str | None) -> dict[str, str]:
|
|
29
|
+
if not client:
|
|
30
|
+
return {}
|
|
31
|
+
targets = {"claude", "antigravity", "gemini"} if client == "all" else {client}
|
|
32
|
+
files: dict[str, str] = {}
|
|
33
|
+
if "claude" in targets:
|
|
34
|
+
files[".claude/settings.json"] = json.dumps({
|
|
35
|
+
"hooks": {
|
|
36
|
+
"PreToolUse": [
|
|
37
|
+
{
|
|
38
|
+
"matcher": "Write|Edit|MultiEdit|Bash",
|
|
39
|
+
"hooks": [{"type": "command", "command": "unrig hook --client claude"}],
|
|
40
|
+
}
|
|
41
|
+
]
|
|
42
|
+
}
|
|
43
|
+
}, indent=2) + "\n"
|
|
44
|
+
if "antigravity" in targets:
|
|
45
|
+
files[".agents/hooks.json"] = json.dumps({
|
|
46
|
+
"unrig-guard": {
|
|
47
|
+
"PreToolUse": [
|
|
48
|
+
{
|
|
49
|
+
"matcher": "run_command|write_to_file|replace_file_content|multi_replace_file_content|Write|Edit|MultiEdit|Bash",
|
|
50
|
+
"hooks": [{"type": "command", "command": "unrig hook --client antigravity"}],
|
|
51
|
+
}
|
|
52
|
+
],
|
|
53
|
+
"Stop": [
|
|
54
|
+
{"type": "command", "command": "unrig hook --client antigravity"}
|
|
55
|
+
],
|
|
56
|
+
}
|
|
57
|
+
}, indent=2) + "\n"
|
|
58
|
+
if "gemini" in targets:
|
|
59
|
+
files[".gemini/settings.json"] = json.dumps({
|
|
60
|
+
"hooks": {
|
|
61
|
+
"BeforeTool": [
|
|
62
|
+
{
|
|
63
|
+
"hooks": [{"type": "command", "name": "unrig-guard", "command": "unrig hook --client gemini"}]
|
|
64
|
+
}
|
|
65
|
+
]
|
|
66
|
+
}
|
|
67
|
+
}, indent=2) + "\n"
|
|
68
|
+
return files
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def init_workspace(
|
|
72
|
+
repo_root: Path,
|
|
73
|
+
force: bool = False,
|
|
74
|
+
client: str | None = None,
|
|
75
|
+
) -> list[tuple[str, str]]:
|
|
76
|
+
"""Initialize `.unrig.yaml`, `.unrig/` templates, and optional agent-client hook configs in `repo_root`."""
|
|
77
|
+
results: list[tuple[str, str]] = []
|
|
78
|
+
files_to_create: dict[str, str] = {
|
|
79
|
+
".unrig.yaml": (_TEMPLATES_DIR / "unrig.yaml").read_text(encoding="utf-8"),
|
|
80
|
+
".unrig/PROTOCOL.md": (_TEMPLATES_DIR / "PROTOCOL.md").read_text(encoding="utf-8"),
|
|
81
|
+
".unrig/blind_auditor_prompt.md": (_TEMPLATES_DIR / "blind_auditor_prompt.md").read_text(encoding="utf-8"),
|
|
82
|
+
".unrig/ratchet.json": json.dumps({"version": 1, "entries": []}, indent=2) + "\n",
|
|
83
|
+
}
|
|
84
|
+
files_to_create.update(_client_hook_files(client))
|
|
85
|
+
|
|
86
|
+
for rel, content in files_to_create.items():
|
|
87
|
+
dest = repo_root / rel
|
|
88
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
89
|
+
if dest.exists() and not force:
|
|
90
|
+
results.append((rel, "skipped (already exists)"))
|
|
91
|
+
continue
|
|
92
|
+
action = "overwritten" if dest.exists() else "created"
|
|
93
|
+
dest.write_text(content, encoding="utf-8")
|
|
94
|
+
results.append((rel, action))
|
|
95
|
+
|
|
96
|
+
return results
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def verify_workspace(
|
|
100
|
+
repo_root: Path,
|
|
101
|
+
config_path: Path | None = None,
|
|
102
|
+
baseline: str | None = None,
|
|
103
|
+
strict_l0: bool = False,
|
|
104
|
+
*,
|
|
105
|
+
record_log: bool = True,
|
|
106
|
+
) -> tuple[bool, list[str]]:
|
|
107
|
+
"""Run all Unrig Level 0 verification checks on `repo_root`."""
|
|
108
|
+
lines: list[str] = []
|
|
109
|
+
try:
|
|
110
|
+
config = load_config(repo_root, config_path)
|
|
111
|
+
except UnrigConfigError as exc:
|
|
112
|
+
return False, [f"[FAIL] [CONFIG_ERROR] {exc}"]
|
|
113
|
+
|
|
114
|
+
l0_blocking, l0_warnings = check_l0_integrity(
|
|
115
|
+
repo_root, config.protected_l0_files, strict_committed=strict_l0
|
|
116
|
+
)
|
|
117
|
+
diff_findings, ratchet_errors, clone_warnings, scan_stats = verify_incremental_diff_with_stats(
|
|
118
|
+
repo_root, config, baseline_override=baseline
|
|
119
|
+
)
|
|
120
|
+
scanned_count = scan_stats.scanned
|
|
121
|
+
ratchet_slacks, _ = find_ratchet_slack(repo_root, config)
|
|
122
|
+
report_findings, report_count = verify_reports_and_artifacts(repo_root, config)
|
|
123
|
+
|
|
124
|
+
for w in l0_warnings:
|
|
125
|
+
lines.append(f"[WARN] {w}")
|
|
126
|
+
if scan_stats.shallow_history:
|
|
127
|
+
lines.append(
|
|
128
|
+
"[WARN] [SHALLOW_HISTORY] Shallow git clone fell back to HEAD; baseline history is truncated."
|
|
129
|
+
)
|
|
130
|
+
for cw in clone_warnings:
|
|
131
|
+
lines.append(f"[WARN] {cw}")
|
|
132
|
+
for slack in ratchet_slacks:
|
|
133
|
+
lines.append(
|
|
134
|
+
f"[WARN] [RATCHET_SLACK] '{config.ratchet_file}' allows count={slack.entry.count} for "
|
|
135
|
+
f"{slack.entry.file} ({slack.entry.rule}), but workspace only has {slack.actual_count}. "
|
|
136
|
+
"Run `unrig ratchet --prune` to tighten."
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
all_failures: list[str] = []
|
|
140
|
+
for blk in l0_blocking:
|
|
141
|
+
all_failures.append(f"[FAIL] [{blk['code']}] {blk['path']}: {blk['message']}")
|
|
142
|
+
for rerr in ratchet_errors:
|
|
143
|
+
all_failures.append(f"[FAIL] {rerr}")
|
|
144
|
+
for df in diff_findings:
|
|
145
|
+
all_failures.append(f"[FAIL] [{df.rule_id}] {df.rel_path}:{df.line} -> {df.message}")
|
|
146
|
+
for rf in report_findings:
|
|
147
|
+
all_failures.append(f"[FAIL] {rf}")
|
|
148
|
+
|
|
149
|
+
lines.extend(all_failures)
|
|
150
|
+
stats_suffix = f"skipped_ignored={scan_stats.skipped_ignored}, syntax_fallback={scan_stats.syntax_fallback}"
|
|
151
|
+
if not all_failures:
|
|
152
|
+
lines.append(
|
|
153
|
+
f"[PASS] Unrig verify succeeded (diff_scanned={scanned_count}, junit_reports={report_count}, "
|
|
154
|
+
f"violations=0, {stats_suffix})."
|
|
155
|
+
)
|
|
156
|
+
return True, lines
|
|
157
|
+
|
|
158
|
+
lines.append(
|
|
159
|
+
f"[BLOCKED] Unrig verify failed ({len(all_failures)} blocking finding(s); "
|
|
160
|
+
f"diff_scanned={scanned_count}, junit_reports={report_count}, {stats_suffix})."
|
|
161
|
+
)
|
|
162
|
+
if record_log:
|
|
163
|
+
codes: list[str] = []
|
|
164
|
+
for blk in l0_blocking:
|
|
165
|
+
codes.append(blk["code"])
|
|
166
|
+
for df in diff_findings:
|
|
167
|
+
codes.append(df.rule_id)
|
|
168
|
+
for rf in report_findings:
|
|
169
|
+
m_code = re.match(r"^\[([A-Z0-9_\-]+)\]", rf)
|
|
170
|
+
codes.append(m_code.group(1) if m_code else "REPORT_BLOCKED")
|
|
171
|
+
if ratchet_errors:
|
|
172
|
+
codes.append("RATCHET_ERROR")
|
|
173
|
+
record_intercept_event(
|
|
174
|
+
repo_root,
|
|
175
|
+
source="verify",
|
|
176
|
+
event="verify",
|
|
177
|
+
client="cli",
|
|
178
|
+
outcome="blocked",
|
|
179
|
+
codes=codes or ["VERIFY_BLOCKED"],
|
|
180
|
+
detail=f"{len(all_failures)} blocking finding(s)",
|
|
181
|
+
)
|
|
182
|
+
return False, lines
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
_CACHE_DIR_REL = Path(".unrig") / ".cache"
|
|
186
|
+
_EVENTS_FILE_NAME = "events.jsonl"
|
|
187
|
+
_STOP_STATE_FILE_NAME = "stop_state.json"
|
|
188
|
+
_MAX_STOP_CONTINUE_SAME_REASON = 2
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _ensure_cache_dir(repo_root: Path) -> Path:
|
|
192
|
+
cache_dir = repo_root / _CACHE_DIR_REL
|
|
193
|
+
cache_dir.mkdir(parents=True, exist_ok=True)
|
|
194
|
+
gi = cache_dir / ".gitignore"
|
|
195
|
+
if not gi.exists():
|
|
196
|
+
gi.write_text("*\n", encoding="utf-8")
|
|
197
|
+
return cache_dir
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _events_file(repo_root: Path) -> Path:
|
|
201
|
+
return repo_root / _CACHE_DIR_REL / _EVENTS_FILE_NAME
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def _stop_state_file(repo_root: Path) -> Path:
|
|
205
|
+
return repo_root / _CACHE_DIR_REL / _STOP_STATE_FILE_NAME
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _update_stop_bounce_count(repo_root: Path, conv_id: str, signature: str) -> int:
|
|
209
|
+
"""Increment and return consecutive Stop bounce count for identical failure `signature`."""
|
|
210
|
+
try:
|
|
211
|
+
cache_dir = _ensure_cache_dir(repo_root)
|
|
212
|
+
state_path = cache_dir / _STOP_STATE_FILE_NAME
|
|
213
|
+
state: dict[str, dict[str, Any]] = {}
|
|
214
|
+
if state_path.exists():
|
|
215
|
+
raw = json.loads(state_path.read_text(encoding="utf-8", errors="replace"))
|
|
216
|
+
if isinstance(raw, dict):
|
|
217
|
+
state = raw
|
|
218
|
+
prev = state.get(conv_id)
|
|
219
|
+
if isinstance(prev, dict) and prev.get("signature") == signature:
|
|
220
|
+
count = int(prev.get("count") or 0) + 1
|
|
221
|
+
else:
|
|
222
|
+
count = 1
|
|
223
|
+
state[conv_id] = {"signature": signature, "count": count}
|
|
224
|
+
state_path.write_text(json.dumps(state, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
225
|
+
return count
|
|
226
|
+
except (OSError, ValueError, TypeError):
|
|
227
|
+
return 1
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _clear_stop_bounce_count(repo_root: Path, conv_id: str) -> None:
|
|
231
|
+
try:
|
|
232
|
+
state_path = _stop_state_file(repo_root)
|
|
233
|
+
if not state_path.exists():
|
|
234
|
+
return
|
|
235
|
+
raw = json.loads(state_path.read_text(encoding="utf-8", errors="replace"))
|
|
236
|
+
if isinstance(raw, dict) and conv_id in raw:
|
|
237
|
+
raw.pop(conv_id, None)
|
|
238
|
+
state_path.write_text(json.dumps(raw, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
239
|
+
except (OSError, ValueError, TypeError):
|
|
240
|
+
return
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def record_intercept_event(
|
|
244
|
+
repo_root: Path,
|
|
245
|
+
*,
|
|
246
|
+
source: str,
|
|
247
|
+
event: str,
|
|
248
|
+
client: str,
|
|
249
|
+
outcome: str,
|
|
250
|
+
codes: list[str],
|
|
251
|
+
detail: str = "",
|
|
252
|
+
) -> None:
|
|
253
|
+
"""Append a local-only interception record under `.unrig/.cache/events.jsonl`."""
|
|
254
|
+
if os.environ.get("UNRIG_DISABLE_EVENT_LOG") == "1":
|
|
255
|
+
return
|
|
256
|
+
try:
|
|
257
|
+
_ensure_cache_dir(repo_root)
|
|
258
|
+
entry = {
|
|
259
|
+
"ts": datetime.now(timezone.utc).isoformat(timespec="seconds"),
|
|
260
|
+
"source": source,
|
|
261
|
+
"event": event,
|
|
262
|
+
"client": client,
|
|
263
|
+
"outcome": outcome,
|
|
264
|
+
"codes": sorted(dict.fromkeys(codes)),
|
|
265
|
+
"detail": detail[:200],
|
|
266
|
+
}
|
|
267
|
+
with _events_file(repo_root).open("a", encoding="utf-8") as fh:
|
|
268
|
+
fh.write(json.dumps(entry, ensure_ascii=False) + "\n")
|
|
269
|
+
except OSError:
|
|
270
|
+
return
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def read_intercept_stats(
|
|
274
|
+
repo_root: Path,
|
|
275
|
+
days: int | None = None,
|
|
276
|
+
) -> dict[str, Any]:
|
|
277
|
+
"""Read local interception statistics from `.unrig/.cache/events.jsonl`."""
|
|
278
|
+
path = _events_file(repo_root)
|
|
279
|
+
if not path.exists():
|
|
280
|
+
return {"total": 0, "by_outcome": {}, "by_code": {}, "by_client": {}, "recent": []}
|
|
281
|
+
|
|
282
|
+
cutoff: datetime | None = None
|
|
283
|
+
if days is not None and days >= 0:
|
|
284
|
+
cutoff = datetime.now(timezone.utc) - timedelta(days=days)
|
|
285
|
+
|
|
286
|
+
events: list[dict[str, Any]] = []
|
|
287
|
+
for raw_line in path.read_text(encoding="utf-8", errors="replace").splitlines():
|
|
288
|
+
line = raw_line.strip()
|
|
289
|
+
if not line:
|
|
290
|
+
continue
|
|
291
|
+
try:
|
|
292
|
+
item = json.loads(line)
|
|
293
|
+
except json.JSONDecodeError:
|
|
294
|
+
continue
|
|
295
|
+
if not isinstance(item, dict):
|
|
296
|
+
continue
|
|
297
|
+
if cutoff is not None and isinstance(item.get("ts"), str):
|
|
298
|
+
try:
|
|
299
|
+
ts_val = datetime.fromisoformat(item["ts"])
|
|
300
|
+
if ts_val.tzinfo is None:
|
|
301
|
+
ts_val = ts_val.replace(tzinfo=timezone.utc)
|
|
302
|
+
if ts_val < cutoff:
|
|
303
|
+
continue
|
|
304
|
+
except ValueError:
|
|
305
|
+
pass
|
|
306
|
+
events.append(item)
|
|
307
|
+
|
|
308
|
+
by_outcome: Counter[str] = Counter()
|
|
309
|
+
by_code: Counter[str] = Counter()
|
|
310
|
+
by_client: Counter[str] = Counter()
|
|
311
|
+
for ev in events:
|
|
312
|
+
by_outcome[str(ev.get("outcome") or "unknown")] += 1
|
|
313
|
+
by_client[str(ev.get("client") or "unknown")] += 1
|
|
314
|
+
for code in ev.get("codes") or []:
|
|
315
|
+
by_code[str(code)] += 1
|
|
316
|
+
|
|
317
|
+
return {
|
|
318
|
+
"total": len(events),
|
|
319
|
+
"by_outcome": dict(by_outcome.most_common()),
|
|
320
|
+
"by_code": dict(by_code.most_common()),
|
|
321
|
+
"by_client": dict(by_client.most_common()),
|
|
322
|
+
"recent": events[-10:],
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def clear_intercept_stats(repo_root: Path) -> bool:
|
|
327
|
+
"""Remove `.unrig/.cache/events.jsonl` if present. Returns True if removed."""
|
|
328
|
+
path = _events_file(repo_root)
|
|
329
|
+
if path.exists():
|
|
330
|
+
path.unlink()
|
|
331
|
+
return True
|
|
332
|
+
return False
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def handle_hook_invocation(
|
|
336
|
+
payload_text: str,
|
|
337
|
+
explicit_root: str | None = None,
|
|
338
|
+
explicit_client: str = "auto",
|
|
339
|
+
) -> tuple[int, str, str]:
|
|
340
|
+
"""
|
|
341
|
+
Process a coding-agent hook invocation across Claude Code, Google Antigravity, and Gemini CLI.
|
|
342
|
+
|
|
343
|
+
Returns `(exit_code, stdout_text, stderr_text)`.
|
|
344
|
+
"""
|
|
345
|
+
stripped = payload_text.strip()
|
|
346
|
+
data: object = None
|
|
347
|
+
if stripped:
|
|
348
|
+
try:
|
|
349
|
+
data = json.loads(stripped)
|
|
350
|
+
except json.JSONDecodeError as exc:
|
|
351
|
+
client = explicit_client if explicit_client != "auto" else "claude"
|
|
352
|
+
msg = f"[UNRIG L0 HOOK BLOCKED] Invalid hook JSON payload: {exc}"
|
|
353
|
+
record_intercept_event(
|
|
354
|
+
resolve_hook_repo_root(explicit_root, None),
|
|
355
|
+
source="hook",
|
|
356
|
+
event="PreToolUse",
|
|
357
|
+
client=client,
|
|
358
|
+
outcome="deny",
|
|
359
|
+
codes=["INVALID_HOOK_JSON"],
|
|
360
|
+
detail=msg,
|
|
361
|
+
)
|
|
362
|
+
return format_hook_response(client, "PreToolUse", 2, msg)
|
|
363
|
+
|
|
364
|
+
client = detect_hook_client(data, explicit_client)
|
|
365
|
+
event_name = (
|
|
366
|
+
str(data.get("hookEventName") or data.get("hook_event_name") or "PreToolUse")
|
|
367
|
+
if isinstance(data, dict)
|
|
368
|
+
else "PreToolUse"
|
|
369
|
+
)
|
|
370
|
+
repo_root = resolve_hook_repo_root(explicit_root, data)
|
|
371
|
+
|
|
372
|
+
if client == "antigravity" and event_name == "Stop" and isinstance(data, dict):
|
|
373
|
+
term_reason = str(data.get("terminationReason") or "")
|
|
374
|
+
continuation_active = bool(data.get("continuationActive", False))
|
|
375
|
+
conv_id = str(data.get("conversationId") or "default")
|
|
376
|
+
if continuation_active or (term_reason and term_reason != "NO_TOOL_CALL"):
|
|
377
|
+
return format_hook_response(client, "Stop", 0, "", stop_continue=False)
|
|
378
|
+
passed, lines = verify_workspace(repo_root, record_log=False)
|
|
379
|
+
if not passed:
|
|
380
|
+
summary = "\n".join(lines[-8:])
|
|
381
|
+
codes = [m.group(1) for ln in lines for m in [re.search(r"\[FAIL\]\s+\[([A-Z0-9_\-]+)\]", ln)] if m]
|
|
382
|
+
failure_codes = codes or ["STOP_GATE_BLOCKED"]
|
|
383
|
+
bounce_count = _update_stop_bounce_count(repo_root, conv_id, summary)
|
|
384
|
+
if bounce_count > _MAX_STOP_CONTINUE_SAME_REASON:
|
|
385
|
+
record_intercept_event(
|
|
386
|
+
repo_root,
|
|
387
|
+
source="hook",
|
|
388
|
+
event="Stop",
|
|
389
|
+
client=client,
|
|
390
|
+
outcome="escalated",
|
|
391
|
+
codes=failure_codes,
|
|
392
|
+
detail=f"Released Stop after {_MAX_STOP_CONTINUE_SAME_REASON} identical bounces for human escalation",
|
|
393
|
+
)
|
|
394
|
+
return format_hook_response(client, "Stop", 0, "", stop_continue=False)
|
|
395
|
+
|
|
396
|
+
reason = (
|
|
397
|
+
"[UNRIG STOP GATE] Unrig verification failed. Fix all blocking findings before finishing "
|
|
398
|
+
"(if blocked by a human-only L0 gate or missing external credential/service, stop and ask the maintainer):\n"
|
|
399
|
+
+ summary
|
|
400
|
+
)
|
|
401
|
+
record_intercept_event(
|
|
402
|
+
repo_root,
|
|
403
|
+
source="hook",
|
|
404
|
+
event="Stop",
|
|
405
|
+
client=client,
|
|
406
|
+
outcome="continue",
|
|
407
|
+
codes=failure_codes,
|
|
408
|
+
detail=lines[-1] if lines else "verify failed",
|
|
409
|
+
)
|
|
410
|
+
return format_hook_response(client, "Stop", 1, reason, stop_continue=True)
|
|
411
|
+
_clear_stop_bounce_count(repo_root, conv_id)
|
|
412
|
+
return format_hook_response(client, "Stop", 0, "", stop_continue=False)
|
|
413
|
+
|
|
414
|
+
try:
|
|
415
|
+
config = load_config(repo_root)
|
|
416
|
+
except UnrigConfigError as exc:
|
|
417
|
+
msg = f"[UNRIG L0 HOOK BLOCKED] Invalid .unrig.yaml: {exc}"
|
|
418
|
+
record_intercept_event(
|
|
419
|
+
repo_root,
|
|
420
|
+
source="hook",
|
|
421
|
+
event=event_name,
|
|
422
|
+
client=client,
|
|
423
|
+
outcome="deny",
|
|
424
|
+
codes=["CONFIG_ERROR"],
|
|
425
|
+
detail=msg,
|
|
426
|
+
)
|
|
427
|
+
return format_hook_response(client, event_name, 2, msg)
|
|
428
|
+
|
|
429
|
+
code, msg = evaluate_hook_payload(payload_text, repo_root, config)
|
|
430
|
+
if code != 0:
|
|
431
|
+
hook_code = "NO_VERIFY_BYPASS" if "--no-verify" in msg else "L0_HOOK_BLOCK"
|
|
432
|
+
record_intercept_event(
|
|
433
|
+
repo_root,
|
|
434
|
+
source="hook",
|
|
435
|
+
event=event_name,
|
|
436
|
+
client=client,
|
|
437
|
+
outcome="deny",
|
|
438
|
+
codes=[hook_code],
|
|
439
|
+
detail=msg,
|
|
440
|
+
)
|
|
441
|
+
return format_hook_response(client, event_name, code, msg)
|