harness-builder 1.0.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.
- harness_builder/__init__.py +4 -0
- harness_builder/_bundled_plugin/README.md +31 -0
- harness_builder/_bundled_plugin/agents/codebase-scout.md +29 -0
- harness_builder/_bundled_plugin/agents/simplification-critic.md +29 -0
- harness_builder/_bundled_plugin/agents/socratic-griller.md +29 -0
- harness_builder/_bundled_plugin/agents/zero-trust-verifier.md +33 -0
- harness_builder/_bundled_plugin/hooks/_cmd_policy.py +295 -0
- harness_builder/_bundled_plugin/hooks/harness_gate.py +275 -0
- harness_builder/_bundled_plugin/hooks/post_tool_format.py +74 -0
- harness_builder/_bundled_plugin/hooks/pre_tool_guard.py +107 -0
- harness_builder/_bundled_plugin/hooks/verify_stop.py +174 -0
- harness_builder/_bundled_plugin/hooks.json +39 -0
- harness_builder/_bundled_plugin/plugin.json +25 -0
- harness_builder/_bundled_plugin/rules/AGENTS.md +33 -0
- harness_builder/_bundled_plugin/rules/git_hygiene.md +11 -0
- harness_builder/_bundled_plugin/rules/go_style.md +11 -0
- harness_builder/_bundled_plugin/rules/python_style.md +11 -0
- harness_builder/_bundled_plugin/rules/typescript_style.md +11 -0
- harness_builder/_bundled_plugin/skills/design-gauntlet/SKILL.md +26 -0
- harness_builder/_bundled_plugin/skills/hb-bootstrap/SKILL.md +52 -0
- harness_builder/_bundled_plugin/skills/hb-build/SKILL.md +30 -0
- harness_builder/_bundled_plugin/skills/hb-design/SKILL.md +33 -0
- harness_builder/_bundled_plugin/skills/hb-plan/SKILL.md +27 -0
- harness_builder/_bundled_plugin/skills/hb-ship/SKILL.md +24 -0
- harness_builder/_bundled_plugin/skills/pr-cleanup/SKILL.md +22 -0
- harness_builder/_bundled_plugin/skills/socratic-griller/SKILL.md +21 -0
- harness_builder/_bundled_plugin/skills/spec-scout/SKILL.md +21 -0
- harness_builder/_bundled_plugin/skills/test-craft/SKILL.md +25 -0
- harness_builder/_bundled_plugin/skills/zero-trust-verifier/SKILL.md +26 -0
- harness_builder/_bundled_plugin/templates/design_brief.md +46 -0
- harness_builder/_bundled_plugin/templates/design_full.md +66 -0
- harness_builder/_bundled_plugin/templates/project_agents.md +21 -0
- harness_builder/adapters/__init__.py +1 -0
- harness_builder/adapters/_scaffold_templates.py +169 -0
- harness_builder/adapters/doctor_adapter.py +262 -0
- harness_builder/adapters/fs_adapter.py +283 -0
- harness_builder/adapters/git_adapter.py +98 -0
- harness_builder/adapters/plugin_installer.py +96 -0
- harness_builder/adapters/repo_scan_adapter.py +155 -0
- harness_builder/adapters/scaffolder.py +270 -0
- harness_builder/cli.py +290 -0
- harness_builder/core/__init__.py +1 -0
- harness_builder/core/_manifest_parsers.py +138 -0
- harness_builder/core/_markdown_scan.py +273 -0
- harness_builder/core/_shell_guard.py +216 -0
- harness_builder/core/_symbol_scan.py +264 -0
- harness_builder/core/_ts_scan.py +123 -0
- harness_builder/core/commit_policy.py +180 -0
- harness_builder/core/design_lint.py +271 -0
- harness_builder/core/drift_analyzer.py +170 -0
- harness_builder/core/exceptions.py +81 -0
- harness_builder/core/frontmatter.py +282 -0
- harness_builder/core/plan_compiler.py +186 -0
- harness_builder/core/repo_detector.py +188 -0
- harness_builder/core/schema.py +286 -0
- harness_builder/core/token_budget.py +201 -0
- harness_builder-1.0.0.dist-info/METADATA +118 -0
- harness_builder-1.0.0.dist-info/RECORD +60 -0
- harness_builder-1.0.0.dist-info/WHEEL +4 -0
- harness_builder-1.0.0.dist-info/entry_points.txt +2 -0
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# Harness Builder (Antigravity Plugin)
|
|
2
|
+
|
|
3
|
+
Global Antigravity plugin providing the methodology, rules, progressive-disclosure
|
|
4
|
+
skills, subagents, templates, and lifecycle hooks for `harness-builder`.
|
|
5
|
+
|
|
6
|
+
## Install
|
|
7
|
+
|
|
8
|
+
```bash
|
|
9
|
+
agy plugin install ./plugin
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
Initialize any target Git repository with thin project-local configuration using
|
|
13
|
+
the companion `hb` CLI:
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
hb init --name my-app --stack python .
|
|
17
|
+
hb check --plugin-dir ./plugin .
|
|
18
|
+
hb doctor .
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## Components
|
|
22
|
+
|
|
23
|
+
- **`rules/`**: Always-on orchestrator router (`AGENTS.md`, `git_hygiene.md`) plus
|
|
24
|
+
on-demand language guides (`python_style.md`, `typescript_style.md`, `go_style.md`).
|
|
25
|
+
- **`skills/`**: 4 stage routers (`hb-design`, `hb-plan`, `hb-build`, `hb-ship`) and
|
|
26
|
+
6 specialist skills (`spec-scout`, `socratic-griller`, `zero-trust-verifier`,
|
|
27
|
+
`test-craft`, `design-gauntlet`, `pr-cleanup`).
|
|
28
|
+
- **`agents/`**: 4 sandboxed subagents (`codebase-scout`, `socratic-griller`,
|
|
29
|
+
`zero-trust-verifier`, `simplification-critic`).
|
|
30
|
+
- **`templates/`**: Thin project `AGENTS.md` and Tier 2/3 design templates.
|
|
31
|
+
- **`hooks/`**: Stdlib-only `PreToolUse`, `PostToolUse`, and `Stop` lifecycle guards.
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: codebase-scout
|
|
3
|
+
description: Read-only explorer that maps entrypoints, public symbols, dependencies, and test infrastructure before design or planning.
|
|
4
|
+
subagent: true
|
|
5
|
+
mainAgent: false
|
|
6
|
+
model: flash
|
|
7
|
+
commandExecutionPolicy: sandbox
|
|
8
|
+
tools:
|
|
9
|
+
- view_file
|
|
10
|
+
- list_dir
|
|
11
|
+
- find_by_name
|
|
12
|
+
- grep_search
|
|
13
|
+
---
|
|
14
|
+
# Codebase Scout
|
|
15
|
+
|
|
16
|
+
You are a fast, strictly read-only codebase reconnaissance specialist.
|
|
17
|
+
|
|
18
|
+
## Mission
|
|
19
|
+
Explore the repository before Tier 2 or Tier 3 design/planning and return a
|
|
20
|
+
compact, factual map of:
|
|
21
|
+
1. Relevant modules, entrypoints, and architectural boundaries.
|
|
22
|
+
2. Public symbols, schemas, and invariants that must stay compatible.
|
|
23
|
+
3. Dependency constraints, build/lint/typecheck tooling, and test layout.
|
|
24
|
+
4. Security or coupling risks relevant to the requested change.
|
|
25
|
+
|
|
26
|
+
## Rules
|
|
27
|
+
- Never modify files or invent symbols you did not observe directly.
|
|
28
|
+
- Cite exact relative file paths and symbol names.
|
|
29
|
+
- Keep your final brief concise (`<= 40` lines) so the parent context stays lean.
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: simplification-critic
|
|
3
|
+
description: Complexity and pragmatic-alternatives architect for Tier 3 design gauntlets who challenges over-engineering and unnecessary abstractions.
|
|
4
|
+
subagent: true
|
|
5
|
+
mainAgent: false
|
|
6
|
+
model: inherit
|
|
7
|
+
commandExecutionPolicy: sandbox
|
|
8
|
+
tools:
|
|
9
|
+
- view_file
|
|
10
|
+
- list_dir
|
|
11
|
+
- find_by_name
|
|
12
|
+
- grep_search
|
|
13
|
+
---
|
|
14
|
+
# Simplification Critic
|
|
15
|
+
|
|
16
|
+
You are a pragmatic systems architect serving as the anti-bloat lens in Tier 3
|
|
17
|
+
`design-gauntlet` reviews.
|
|
18
|
+
|
|
19
|
+
## Mission
|
|
20
|
+
Challenge every proposed abstraction, layer, config flag, and dependency in a
|
|
21
|
+
design document to determine whether a simpler, flatter, stdlib-first approach
|
|
22
|
+
delivers the same reliability with less maintenance cost.
|
|
23
|
+
|
|
24
|
+
## Rules
|
|
25
|
+
- Identify premature generalizations, speculative extensibility, duplicate state,
|
|
26
|
+
and oversized PR slices (`>= 400` LOC).
|
|
27
|
+
- For every critique, propose a concrete simpler alternative and state the exact
|
|
28
|
+
trade-off.
|
|
29
|
+
- Output concise **Must Simplify**, **Optional Trim**, and **Keep As-Is** sections.
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: socratic-griller
|
|
3
|
+
description: Focused interrogator persona that resolves ambiguous requirements, edge cases, and non-goals in 1-3 crisp questions with recommended defaults.
|
|
4
|
+
subagent: true
|
|
5
|
+
mainAgent: false
|
|
6
|
+
model: inherit
|
|
7
|
+
commandExecutionPolicy: sandbox
|
|
8
|
+
tools:
|
|
9
|
+
- view_file
|
|
10
|
+
- list_dir
|
|
11
|
+
- find_by_name
|
|
12
|
+
- grep_search
|
|
13
|
+
---
|
|
14
|
+
# Socratic Griller
|
|
15
|
+
|
|
16
|
+
You are a disciplined principal engineer conducting pre-design requirement
|
|
17
|
+
clarification.
|
|
18
|
+
|
|
19
|
+
## Mission
|
|
20
|
+
Eliminate ambiguity, implicit assumptions, and hidden scope traps BEFORE a
|
|
21
|
+
design document is drafted.
|
|
22
|
+
|
|
23
|
+
## Rules
|
|
24
|
+
- Inspect existing code first; never ask questions the repository already answers.
|
|
25
|
+
- Ask **1–3 high-leverage questions per round**, each paired with a concrete
|
|
26
|
+
**recommended default**.
|
|
27
|
+
- Respect Tier 2 limits (1–2 rounds max); stop immediately once scope,
|
|
28
|
+
non-goals, error semantics, and interfaces are clear.
|
|
29
|
+
- Return a concise list of resolved decisions, non-goals, and constraints.
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: zero-trust-verifier
|
|
3
|
+
description: Skeptical principal auditor for falsifiable acceptance rubrics and fresh-context adversarial diff audits backed by real command evidence.
|
|
4
|
+
subagent: true
|
|
5
|
+
mainAgent: false
|
|
6
|
+
model: pro
|
|
7
|
+
commandExecutionPolicy: sandbox
|
|
8
|
+
tools:
|
|
9
|
+
- view_file
|
|
10
|
+
- list_dir
|
|
11
|
+
- find_by_name
|
|
12
|
+
- grep_search
|
|
13
|
+
- run_command
|
|
14
|
+
---
|
|
15
|
+
# Zero-Trust Verifier
|
|
16
|
+
|
|
17
|
+
You are an independent, skeptical principal software auditor operating in fresh
|
|
18
|
+
context. Treat every unverified claim as unproven.
|
|
19
|
+
|
|
20
|
+
## Mission
|
|
21
|
+
1. **Rubric Mode:** Author or tighten falsifiable acceptance criteria with
|
|
22
|
+
explicit pass/fail invariants, runnable verification commands, and negative
|
|
23
|
+
controls.
|
|
24
|
+
2. **Audit Mode:** Inspect `git diff`, design contracts, and `scorecard.json`;
|
|
25
|
+
run tests, linters, typechecks, and `hb drift` directly; probe boundary
|
|
26
|
+
conditions and security invariants.
|
|
27
|
+
|
|
28
|
+
## Rules
|
|
29
|
+
- Never trust author summaries without running commands and inspecting outputs.
|
|
30
|
+
- Flag tautological mocks, missing negative tests, path/symlink traversal risks,
|
|
31
|
+
`shell=True`, silent failures, and contract drift.
|
|
32
|
+
- Return a clear `PASS` or `FAIL` verdict with exact file/line repros and
|
|
33
|
+
verbatim command outputs.
|
|
@@ -0,0 +1,295 @@
|
|
|
1
|
+
"""Internal stdlib-only command safety and Git commit hygiene checks for PreToolUse."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
import shlex
|
|
7
|
+
import subprocess
|
|
8
|
+
from collections.abc import Sequence
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
import harness_gate as gate
|
|
13
|
+
|
|
14
|
+
_PROD_EXTS = frozenset({
|
|
15
|
+
".py", ".pyi", ".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".go", ".rs",
|
|
16
|
+
".java", ".kt", ".c", ".cc", ".cpp", ".h", ".hpp", ".cs", ".rb", ".swift",
|
|
17
|
+
})
|
|
18
|
+
_TEST_DIRS = frozenset({"tests", "test", "__tests__", "spec", "specs"})
|
|
19
|
+
_CATASTROPHIC_RM = frozenset({"/", "/*", "~", "~/", "$HOME", "${HOME}", ".", ".."})
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def split_shell_segments(command: str) -> list[str]:
|
|
23
|
+
"""Split chained shell commands on `&&`, `||`, `;`, `|`, and newlines respecting quotes."""
|
|
24
|
+
segs: list[str] = []
|
|
25
|
+
buf: list[str] = []
|
|
26
|
+
q = ""
|
|
27
|
+
i, n = 0, len(command)
|
|
28
|
+
while i < n:
|
|
29
|
+
ch = command[i]
|
|
30
|
+
if q:
|
|
31
|
+
if ch == "\\" and q == '"' and i + 1 < n:
|
|
32
|
+
buf.append(command[i : i + 2])
|
|
33
|
+
i += 2
|
|
34
|
+
continue
|
|
35
|
+
if ch == q:
|
|
36
|
+
q = ""
|
|
37
|
+
buf.append(ch)
|
|
38
|
+
i += 1
|
|
39
|
+
elif ch in ("'", '"'):
|
|
40
|
+
q = ch
|
|
41
|
+
buf.append(ch)
|
|
42
|
+
i += 1
|
|
43
|
+
elif ch == "\\" and i + 1 < n:
|
|
44
|
+
buf.append(command[i : i + 2])
|
|
45
|
+
i += 2
|
|
46
|
+
elif command.startswith(("&&", "||"), i):
|
|
47
|
+
segs.append("".join(buf).strip())
|
|
48
|
+
buf.clear()
|
|
49
|
+
i += 2
|
|
50
|
+
elif ch in (";", "|", "\n"):
|
|
51
|
+
segs.append("".join(buf).strip())
|
|
52
|
+
buf.clear()
|
|
53
|
+
i += 1
|
|
54
|
+
else:
|
|
55
|
+
buf.append(ch)
|
|
56
|
+
i += 1
|
|
57
|
+
if tail := "".join(buf).strip():
|
|
58
|
+
segs.append(tail)
|
|
59
|
+
return [s for s in segs if s]
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def tokenize_segment(seg: str) -> list[str]:
|
|
63
|
+
"""Tokenize a single shell segment and strip leading env/wrapper prefixes."""
|
|
64
|
+
try:
|
|
65
|
+
tokens = shlex.split(seg)
|
|
66
|
+
except ValueError:
|
|
67
|
+
tokens = [t.strip("\"'") for t in seg.split() if t.strip("\"'")]
|
|
68
|
+
idx = 0
|
|
69
|
+
while idx < len(tokens) and "=" in tokens[idx] and not tokens[idx].startswith("-"):
|
|
70
|
+
if tokens[idx].split("=", 1)[0].isidentifier():
|
|
71
|
+
idx += 1
|
|
72
|
+
else:
|
|
73
|
+
break
|
|
74
|
+
if idx < len(tokens) and tokens[idx] in {"env", "sudo", "command"}:
|
|
75
|
+
idx += 1
|
|
76
|
+
while idx < len(tokens) and (tokens[idx].startswith("-") or "=" in tokens[idx]):
|
|
77
|
+
idx += 1
|
|
78
|
+
return tokens[idx:]
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _is_test_file(rel_path: str) -> bool:
|
|
82
|
+
norm = rel_path.replace("\\", "/").lower()
|
|
83
|
+
parts = [p for p in norm.split("/") if p]
|
|
84
|
+
if any(p in _TEST_DIRS for p in parts[:-1]):
|
|
85
|
+
return True
|
|
86
|
+
name = parts[-1] if parts else ""
|
|
87
|
+
if name.startswith("test_") or name.endswith("_test.py") or name.endswith("_test.go"):
|
|
88
|
+
return True
|
|
89
|
+
return any(tok in name for tok in (".test.", ".spec.")) or name == "conftest.py"
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _is_prod_file(rel_path: str) -> bool:
|
|
93
|
+
return not _is_test_file(rel_path) and Path(rel_path).suffix.lower() in _PROD_EXTS
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _run_git(cwd: Path, args: Sequence[str]) -> tuple[int, str]:
|
|
97
|
+
try:
|
|
98
|
+
proc = subprocess.run(
|
|
99
|
+
["git", *args], cwd=cwd, capture_output=True, text=True,
|
|
100
|
+
timeout=3, shell=False, check=False,
|
|
101
|
+
)
|
|
102
|
+
return proc.returncode, proc.stdout
|
|
103
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
104
|
+
return 1, ""
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _check_git_push(tokens: list[str], cwd: Path, blocked_branches: Sequence[str]) -> str | None:
|
|
108
|
+
if not blocked_branches:
|
|
109
|
+
return None
|
|
110
|
+
blocked = set(blocked_branches)
|
|
111
|
+
is_force = is_mirror = is_delete = False
|
|
112
|
+
pos: list[str] = []
|
|
113
|
+
i = 2
|
|
114
|
+
while i < len(tokens):
|
|
115
|
+
t = tokens[i]
|
|
116
|
+
if t in {"-f", "--force", "--force-with-lease", "--force-if-includes"} or (
|
|
117
|
+
t.startswith(("--force-with-lease=", "--force-if-includes="))
|
|
118
|
+
):
|
|
119
|
+
is_force = True
|
|
120
|
+
elif t == "--mirror":
|
|
121
|
+
is_mirror = True
|
|
122
|
+
elif t in {"-d", "--delete"}:
|
|
123
|
+
is_delete = True
|
|
124
|
+
elif t.startswith("-") and not t.startswith("--") and ("f" in t[1:] or "d" in t[1:]):
|
|
125
|
+
is_force = is_force or ("f" in t[1:])
|
|
126
|
+
is_delete = is_delete or ("d" in t[1:])
|
|
127
|
+
elif t in {"-o", "--push-option", "--repo", "--receive-pack", "--exec"}:
|
|
128
|
+
i += 1
|
|
129
|
+
elif not t.startswith("-"):
|
|
130
|
+
pos.append(t)
|
|
131
|
+
i += 1
|
|
132
|
+
if is_mirror:
|
|
133
|
+
return "protected_branch_force_push: git push --mirror is blocked on protected repos."
|
|
134
|
+
targets: list[str] = []
|
|
135
|
+
for ref in (pos[1:] if len(pos) >= 2 else []):
|
|
136
|
+
if ref.startswith("+"):
|
|
137
|
+
is_force = True
|
|
138
|
+
ref = ref[1:]
|
|
139
|
+
if ref.startswith(":"):
|
|
140
|
+
is_delete = True
|
|
141
|
+
dst = ref[1:].removeprefix("refs/heads/")
|
|
142
|
+
else:
|
|
143
|
+
dst = (ref.split(":", 1)[1] if ":" in ref else ref).removeprefix("refs/heads/")
|
|
144
|
+
if dst:
|
|
145
|
+
targets.append(dst)
|
|
146
|
+
if not (is_force or is_delete):
|
|
147
|
+
return None
|
|
148
|
+
if not targets:
|
|
149
|
+
rc, out = _run_git(cwd, ["rev-parse", "--abbrev-ref", "HEAD"])
|
|
150
|
+
if rc == 0 and out.strip():
|
|
151
|
+
targets.append(out.strip())
|
|
152
|
+
for br in targets:
|
|
153
|
+
if br in blocked:
|
|
154
|
+
return f"protected_branch_force_push: destructive push to protected branch '{br}'."
|
|
155
|
+
return None
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _extract_commit_message(tokens: list[str]) -> str | None:
|
|
159
|
+
msgs: list[str] = []
|
|
160
|
+
i = 2
|
|
161
|
+
while i < len(tokens):
|
|
162
|
+
t = tokens[i]
|
|
163
|
+
if t in {"-m", "--message"} and i + 1 < len(tokens):
|
|
164
|
+
msgs.append(tokens[i + 1])
|
|
165
|
+
i += 2
|
|
166
|
+
continue
|
|
167
|
+
if t.startswith("--message="):
|
|
168
|
+
msgs.append(t.split("=", 1)[1])
|
|
169
|
+
elif t.startswith("-m") and len(t) > 2:
|
|
170
|
+
msgs.append(t[2:])
|
|
171
|
+
i += 1
|
|
172
|
+
return "\n".join(msgs) if msgs else None
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _check_git_commit(tokens: list[str], cwd: Path, git_pol: dict[str, Any]) -> str | None:
|
|
176
|
+
if any(t in {"-h", "--help"} for t in tokens[2:]):
|
|
177
|
+
return None
|
|
178
|
+
msg = _extract_commit_message(tokens)
|
|
179
|
+
if msg is not None:
|
|
180
|
+
subject = next((ln.strip() for ln in msg.splitlines() if ln.strip()), "")
|
|
181
|
+
max_len = int(git_pol["max_subject_length"])
|
|
182
|
+
if len(subject) > max_len:
|
|
183
|
+
return f"commit_subject_length: subject ({len(subject)} chars) exceeds {max_len}."
|
|
184
|
+
pat = str(git_pol["commit_subject_regex"] or "")
|
|
185
|
+
if pat:
|
|
186
|
+
try:
|
|
187
|
+
if not re.search(pat, subject):
|
|
188
|
+
return f"commit_subject_regex: subject {subject!r} does not match {pat!r}."
|
|
189
|
+
except re.error:
|
|
190
|
+
pass
|
|
191
|
+
include_all = any(
|
|
192
|
+
t in {"-a", "--all"} or (t.startswith("-") and not t.startswith("--") and "a" in t[1:])
|
|
193
|
+
for t in tokens[2:]
|
|
194
|
+
)
|
|
195
|
+
rc, raw_files = _run_git(cwd, ["diff", "--cached", "--name-only", "-z"])
|
|
196
|
+
staged = [f for f in raw_files.split("\x00") if f] if rc == 0 else []
|
|
197
|
+
if include_all:
|
|
198
|
+
rc2, raw_mod = _run_git(cwd, ["diff", "--name-only", "-z"])
|
|
199
|
+
if rc2 == 0:
|
|
200
|
+
staged = sorted(set(staged) | {f for f in raw_mod.split("\x00") if f})
|
|
201
|
+
if git_pol["require_test_pairing"] and staged:
|
|
202
|
+
if any(_is_prod_file(f) for f in staged) and not any(_is_test_file(f) for f in staged):
|
|
203
|
+
return "test_pairing: production code staged without paired test files."
|
|
204
|
+
total_lines = 0
|
|
205
|
+
diff_cmds = [["diff", "--cached", "--numstat"]]
|
|
206
|
+
if include_all:
|
|
207
|
+
diff_cmds.append(["diff", "--numstat"])
|
|
208
|
+
for dcmd in diff_cmds:
|
|
209
|
+
rc_n, numstat = _run_git(cwd, dcmd)
|
|
210
|
+
if rc_n == 0:
|
|
211
|
+
for line in numstat.splitlines():
|
|
212
|
+
parts = line.split("\t")
|
|
213
|
+
if len(parts) >= 2 and parts[0].isdigit() and parts[1].isdigit():
|
|
214
|
+
total_lines += int(parts[0]) + int(parts[1])
|
|
215
|
+
max_lines = int(git_pol["max_commit_lines"])
|
|
216
|
+
if total_lines > max_lines:
|
|
217
|
+
return f"commit_line_budget: staged diff ({total_lines} lines) exceeds limit ({max_lines})."
|
|
218
|
+
return None
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _check_mv(
|
|
222
|
+
args: list[str], protected: Sequence[str], gov_root: Path, cmd_cwd: Path, label: str,
|
|
223
|
+
) -> str | None:
|
|
224
|
+
for src in args[:-1]:
|
|
225
|
+
if gate.is_protected_match(src, protected, root=gov_root, cwd=cmd_cwd):
|
|
226
|
+
return f"protected_delete: {label} on protected path '{src}' is blocked."
|
|
227
|
+
if len(args) >= 2 and not args[-1].endswith("/"):
|
|
228
|
+
dst_norm = gate.normalize_rel_path(args[-1], root=gov_root, cwd=cmd_cwd)
|
|
229
|
+
if dst_norm in {gate.normalize_rel_path(p) for p in protected}:
|
|
230
|
+
return f"protected_delete: {label} overwrites protected path '{args[-1]}'."
|
|
231
|
+
return None
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def check_command(
|
|
235
|
+
command: str, cmd_cwd: Path, gov_root: Path, cfg: dict[str, Any],
|
|
236
|
+
) -> str | None:
|
|
237
|
+
"""Evaluate a shell command string against protected deletes, force-push, and commit policy."""
|
|
238
|
+
protected = cfg["guards"]["protected_files"]
|
|
239
|
+
git_pol = cfg["git_policy"]
|
|
240
|
+
for seg in split_shell_segments(command):
|
|
241
|
+
tokens = tokenize_segment(seg)
|
|
242
|
+
if not tokens:
|
|
243
|
+
continue
|
|
244
|
+
cmd = Path(tokens[0]).name
|
|
245
|
+
if cmd in {"rm", "unlink", "shred"}:
|
|
246
|
+
flags = [t for t in tokens[1:] if t.startswith("-")]
|
|
247
|
+
args = [t for t in tokens[1:] if not t.startswith("-")]
|
|
248
|
+
recursive = any(
|
|
249
|
+
f in {"-r", "-R", "--recursive"}
|
|
250
|
+
or (not f.startswith("--") and ("r" in f[1:] or "R" in f[1:]))
|
|
251
|
+
for f in flags
|
|
252
|
+
)
|
|
253
|
+
for arg in args:
|
|
254
|
+
norm_a = arg.rstrip("/")
|
|
255
|
+
if recursive and (
|
|
256
|
+
norm_a in {"", ".", "..", "~", "$HOME", "${HOME}", ".git"}
|
|
257
|
+
or norm_a.endswith("/.git")
|
|
258
|
+
or arg in _CATASTROPHIC_RM
|
|
259
|
+
):
|
|
260
|
+
return f"dangerous_rm: catastrophic recursive delete '{arg}' is blocked."
|
|
261
|
+
if gate.is_protected_match(arg, protected, root=gov_root, cwd=cmd_cwd):
|
|
262
|
+
return f"protected_delete: deleting protected path '{arg}' is blocked."
|
|
263
|
+
elif cmd == "mv":
|
|
264
|
+
args = [t for t in tokens[1:] if not t.startswith("-")]
|
|
265
|
+
if reason := _check_mv(args, protected, gov_root, cmd_cwd, "mv"):
|
|
266
|
+
return reason
|
|
267
|
+
elif cmd == "git":
|
|
268
|
+
g_tokens, i, eff_cwd = [tokens[0]], 1, cmd_cwd
|
|
269
|
+
while i < len(tokens) and tokens[i].startswith("-"):
|
|
270
|
+
if tokens[i] in {"-C", "-c", "--git-dir", "--work-tree"} and i + 1 < len(tokens):
|
|
271
|
+
if tokens[i] == "-C":
|
|
272
|
+
eff_cwd = (eff_cwd / tokens[i + 1]).resolve(strict=False)
|
|
273
|
+
i += 2
|
|
274
|
+
else:
|
|
275
|
+
i += 1
|
|
276
|
+
g_tokens.extend(tokens[i:])
|
|
277
|
+
if len(g_tokens) < 2:
|
|
278
|
+
continue
|
|
279
|
+
sub = g_tokens[1]
|
|
280
|
+
if sub == "rm":
|
|
281
|
+
for arg in [t for t in g_tokens[2:] if not t.startswith("-")]:
|
|
282
|
+
if gate.is_protected_match(arg, protected, root=gov_root, cwd=eff_cwd):
|
|
283
|
+
return f"protected_delete: git rm on protected path '{arg}' is blocked."
|
|
284
|
+
elif sub == "mv":
|
|
285
|
+
args = [t for t in g_tokens[2:] if not t.startswith("-")]
|
|
286
|
+
if reason := _check_mv(args, protected, gov_root, eff_cwd, "git mv"):
|
|
287
|
+
return reason
|
|
288
|
+
elif sub == "push":
|
|
289
|
+
branches = git_pol["block_force_push_branches"]
|
|
290
|
+
if reason := _check_git_push(g_tokens, eff_cwd, branches):
|
|
291
|
+
return reason
|
|
292
|
+
elif sub == "commit":
|
|
293
|
+
if reason := _check_git_commit(g_tokens, eff_cwd, git_pol):
|
|
294
|
+
return reason
|
|
295
|
+
return None
|