lockmaster 0.0.1__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.
- lockmaster/__init__.py +3 -0
- lockmaster/__main__.py +3 -0
- lockmaster/cli.py +225 -0
- lockmaster/config.py +195 -0
- lockmaster/doctor.py +146 -0
- lockmaster/drivers.py +93 -0
- lockmaster/generated.py +65 -0
- lockmaster/git.py +102 -0
- lockmaster/install.py +229 -0
- lockmaster/kit/claude/hooks/auto-land.py +286 -0
- lockmaster/kit/claude/hooks/block-main.py +174 -0
- lockmaster/kit/claude/hooks/claim-guard.py +133 -0
- lockmaster/kit/claude/hooks/disk-budget.py +199 -0
- lockmaster/kit/claude/hooks/guard-open-work-inbox.sh +17 -0
- lockmaster/kit/claude/hooks/inject-inbox.sh +54 -0
- lockmaster/kit/claude/hooks/now-ledger.py +371 -0
- lockmaster/kit/claude/hooks/release-locks.sh +34 -0
- lockmaster/kit/claude/hooks/require-progress.sh +15 -0
- lockmaster/kit/claude/hooks/session-lock.sh +58 -0
- lockmaster/kit/claude/hooks/stop-if-blocked.sh +20 -0
- lockmaster/kit/claude/hooks/work-files.py +128 -0
- lockmaster/kit/claude/hooks/worktree-cleanup.py +159 -0
- lockmaster/kit/claude/settings.json +197 -0
- lockmaster/kit/claude/skills/docket/SKILL.md +89 -0
- lockmaster/kit/claude/skills/landing/SKILL.md +68 -0
- lockmaster/kit/work/BACKLOG.md +12 -0
- lockmaster/kit/work/INTERVIEW.md +22 -0
- lockmaster/kit/work/LESSONS.md +12 -0
- lockmaster/kit/work/MACHINE.md +20 -0
- lockmaster/kit/work/OPEN-WORK.md +24 -0
- lockmaster/kit/work/WORKLOG.md +24 -0
- lockmaster/land.py +1328 -0
- lockmaster/merge.py +99 -0
- lockmaster/now.py +92 -0
- lockmaster/repo.py +268 -0
- lockmaster/status.py +119 -0
- lockmaster/surface.py +102 -0
- lockmaster-0.0.1.dist-info/METADATA +130 -0
- lockmaster-0.0.1.dist-info/RECORD +43 -0
- lockmaster-0.0.1.dist-info/WHEEL +5 -0
- lockmaster-0.0.1.dist-info/entry_points.txt +2 -0
- lockmaster-0.0.1.dist-info/licenses/LICENSE +23 -0
- lockmaster-0.0.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""PreToolUse(Bash) — SR-ARCHITECTURE decision 12: only lockmaster writes to main.
|
|
3
|
+
|
|
4
|
+
An agent's `git commit` (or merge, cherry-pick, revert, am, rebase) while
|
|
5
|
+
`main` is checked out is refused, with the way round: `lockmaster start` /
|
|
6
|
+
`lockmaster submit`. lockmaster's own landing runs git from inside
|
|
7
|
+
`lockmaster`, never through the agent's Bash tool, so it is not seen here.
|
|
8
|
+
|
|
9
|
+
A `git push` that updates `main` passes only when it is plain: every option
|
|
10
|
+
is on SAFE_PUSH_OPTIONS and no refspec forces (`+`) or deletes (`:main`), so
|
|
11
|
+
the remote takes it only as a fast-forward of what lockmaster landed
|
|
12
|
+
(ruled by the decider, 2026-10-26). Anything else that would update `main`
|
|
13
|
+
is refused. An allow-list, so an option this hook does not know is refused.
|
|
14
|
+
|
|
15
|
+
A heredoc's body is text, not commands, and is not judged.
|
|
16
|
+
|
|
17
|
+
It binds agent sessions only: it is a Claude Code hook, so the decider's own
|
|
18
|
+
terminal is untouched and can still commit to main by hand (W-05 hazard).
|
|
19
|
+
The branch is `lockmaster.toml` `[main] branch`, else `main`.
|
|
20
|
+
Standard library only; it does not need lockmaster installed.
|
|
21
|
+
"""
|
|
22
|
+
import json
|
|
23
|
+
import os
|
|
24
|
+
import re
|
|
25
|
+
import shlex
|
|
26
|
+
import subprocess
|
|
27
|
+
import sys
|
|
28
|
+
|
|
29
|
+
WRITES = ("commit", "merge", "cherry-pick", "revert", "am", "rebase")
|
|
30
|
+
HARMLESS = ("--abort", "--quit", "-h", "--help")
|
|
31
|
+
# The only options a push that updates main may carry.
|
|
32
|
+
SAFE_PUSH_OPTIONS = {"-u", "--set-upstream", "-q", "--quiet", "-v", "--verbose", "--atomic",
|
|
33
|
+
"--follow-tags", "--no-follow-tags", "--porcelain", "--progress", "--no-progress"}
|
|
34
|
+
HEREDOC_RE = re.compile(r"<<-?\s*(['\"]?)([A-Za-z_][A-Za-z0-9_]*)\1")
|
|
35
|
+
OPERATORS = {"&&", "||", ";", "|", "&", ";;", "|&"}
|
|
36
|
+
# git's global options that take a value as the next word.
|
|
37
|
+
VALUED = {"-C", "-c", "--git-dir", "--work-tree", "--namespace", "--exec-path", "--config-env"}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def git(args, cwd):
|
|
41
|
+
try:
|
|
42
|
+
r = subprocess.run(["git"] + args, cwd=cwd, capture_output=True, text=True)
|
|
43
|
+
except OSError:
|
|
44
|
+
return None
|
|
45
|
+
return r.stdout.strip() if r.returncode == 0 else None
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def main_branch(cwd):
|
|
49
|
+
top = git(["rev-parse", "--show-toplevel"], cwd)
|
|
50
|
+
if top:
|
|
51
|
+
root = git(["worktree", "list", "--porcelain"], top)
|
|
52
|
+
first = root.splitlines()[0][len("worktree "):] if root else top
|
|
53
|
+
try:
|
|
54
|
+
text = open(os.path.join(first, "lockmaster.toml"), encoding="utf-8").read()
|
|
55
|
+
except OSError:
|
|
56
|
+
text = ""
|
|
57
|
+
m = re.search(r"^\[main\][^\[]*?^branch\s*=\s*[\"']([^\"']+)[\"']", text, re.M | re.S)
|
|
58
|
+
if m:
|
|
59
|
+
return m.group(1)
|
|
60
|
+
return "main"
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def without_heredocs(command):
|
|
64
|
+
"""The command with every heredoc body taken out: those lines are input, not commands."""
|
|
65
|
+
out, ending = [], []
|
|
66
|
+
for line in command.split("\n"):
|
|
67
|
+
if ending:
|
|
68
|
+
if line.strip() == ending[0]:
|
|
69
|
+
ending.pop(0)
|
|
70
|
+
continue
|
|
71
|
+
out.append(line)
|
|
72
|
+
ending = [m.group(2) for m in HEREDOC_RE.finditer(line)]
|
|
73
|
+
return "\n".join(out)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def segments(command):
|
|
77
|
+
command = without_heredocs(command)
|
|
78
|
+
lexer = shlex.shlex(command.replace("\n", " ; "), posix=True, punctuation_chars=True)
|
|
79
|
+
lexer.whitespace_split = True
|
|
80
|
+
seg = []
|
|
81
|
+
try:
|
|
82
|
+
for tok in lexer:
|
|
83
|
+
if tok in OPERATORS:
|
|
84
|
+
if seg:
|
|
85
|
+
yield seg
|
|
86
|
+
seg = []
|
|
87
|
+
else:
|
|
88
|
+
seg.append(tok)
|
|
89
|
+
except ValueError: # unbalanced quotes: judge what was read
|
|
90
|
+
pass
|
|
91
|
+
if seg:
|
|
92
|
+
yield seg
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def refused(command, cwd):
|
|
96
|
+
"""The reason this command writes to main, or None."""
|
|
97
|
+
for seg in segments(command):
|
|
98
|
+
while seg and re.match(r"^[A-Za-z_][A-Za-z0-9_]*=", seg[0]):
|
|
99
|
+
seg = seg[1:] # VAR=value prefixes
|
|
100
|
+
while seg and seg[0] in ("command", "env", "sudo", "exec", "nohup", "time"):
|
|
101
|
+
seg = seg[1:]
|
|
102
|
+
if not seg:
|
|
103
|
+
continue
|
|
104
|
+
if seg[0] == "cd":
|
|
105
|
+
target = os.path.expanduser(seg[1]) if len(seg) > 1 else os.path.expanduser("~")
|
|
106
|
+
cwd = os.path.normpath(os.path.join(cwd, target))
|
|
107
|
+
continue
|
|
108
|
+
if os.path.basename(seg[0]) != "git":
|
|
109
|
+
continue
|
|
110
|
+
here, i = cwd, 1
|
|
111
|
+
while i < len(seg) and seg[i].startswith("-"):
|
|
112
|
+
opt = seg[i]
|
|
113
|
+
if opt == "-C" and i + 1 < len(seg):
|
|
114
|
+
here = os.path.normpath(os.path.join(here, os.path.expanduser(seg[i + 1])))
|
|
115
|
+
if opt in VALUED:
|
|
116
|
+
i += 2
|
|
117
|
+
else:
|
|
118
|
+
i += 1
|
|
119
|
+
if i >= len(seg):
|
|
120
|
+
continue
|
|
121
|
+
sub, rest = seg[i], seg[i + 1:]
|
|
122
|
+
if not os.path.isdir(here):
|
|
123
|
+
continue
|
|
124
|
+
main = main_branch(here)
|
|
125
|
+
current = git(["symbolic-ref", "--short", "-q", "HEAD"], here)
|
|
126
|
+
if sub in WRITES and current == main and not any(a in HARMLESS for a in rest):
|
|
127
|
+
return "`git {}` on {}".format(sub, main)
|
|
128
|
+
if sub == "push":
|
|
129
|
+
options = [a for a in rest if a.startswith("-")]
|
|
130
|
+
refspecs = [a for a in rest if not a.startswith("-")][1:]
|
|
131
|
+
targets_main = (not refspecs and current == main) or any(
|
|
132
|
+
o in ("--all", "--mirror", "--branches") for o in options)
|
|
133
|
+
unsafe = []
|
|
134
|
+
for spec in refspecs:
|
|
135
|
+
src, _, dst = spec.lstrip("+").partition(":")
|
|
136
|
+
dst = dst or src
|
|
137
|
+
if dst in (main, "refs/heads/" + main) or (dst == "HEAD" and current == main):
|
|
138
|
+
targets_main = True
|
|
139
|
+
if spec.startswith("+") or (":" in spec and not src):
|
|
140
|
+
unsafe.append(spec)
|
|
141
|
+
if targets_main:
|
|
142
|
+
unsafe += [o for o in options if o not in SAFE_PUSH_OPTIONS]
|
|
143
|
+
if unsafe:
|
|
144
|
+
return "`git push {}` updates {} with {} — only a plain push may".format(
|
|
145
|
+
" ".join(rest), main, ", ".join(unsafe))
|
|
146
|
+
return None
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def main():
|
|
150
|
+
try:
|
|
151
|
+
hook = json.loads(sys.stdin.read() or "{}")
|
|
152
|
+
except ValueError:
|
|
153
|
+
return 0
|
|
154
|
+
command = (hook.get("tool_input") or {}).get("command") or ""
|
|
155
|
+
if "git" not in command:
|
|
156
|
+
return 0
|
|
157
|
+
why = refused(command, hook.get("cwd") or os.getcwd())
|
|
158
|
+
if not why:
|
|
159
|
+
return 0
|
|
160
|
+
print(json.dumps({"hookSpecificOutput": {
|
|
161
|
+
"hookEventName": "PreToolUse",
|
|
162
|
+
"permissionDecision": "deny",
|
|
163
|
+
"permissionDecisionReason": (
|
|
164
|
+
"Refused: {}. Only lockmaster writes to main, and only a plain push sends it "
|
|
165
|
+
"(SR-ARCHITECTURE decision 12). "
|
|
166
|
+
"Work on a change instead: `lockmaster start <W-nn> --paths <path>…`, edit in its "
|
|
167
|
+
"worktree, then `lockmaster submit -m \"…\"` — it lands on main for you. "
|
|
168
|
+
"Edits already made in main's checkout land with `lockmaster save -m \"…\" <path>…`. "
|
|
169
|
+
"The decider can still commit to main by hand from a terminal.").format(why)}}))
|
|
170
|
+
return 0
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
if __name__ == "__main__":
|
|
174
|
+
sys.exit(main())
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""PreToolUse(Write|Edit|MultiEdit|NotebookEdit) — SR-ARCHITECTURE decision 5.
|
|
3
|
+
|
|
4
|
+
A write inside a lockmaster change's worktree to a path outside its claim is
|
|
5
|
+
WARNED, not refused: the hook prints the claim and the path, to the session
|
|
6
|
+
and to the person watching. Only claimed paths land; the rest is left behind,
|
|
7
|
+
so the agent should know before it writes, not after it submits.
|
|
8
|
+
|
|
9
|
+
A write in the primary checkout to a path a live change claims is WARNED too
|
|
10
|
+
(W-10): that uncommitted edit would make the change's landing wait. Edit it in
|
|
11
|
+
the change's worktree, or land it with `lockmaster save`. `work/NOW.md`, the
|
|
12
|
+
live ledger, is left out: it is always edited there.
|
|
13
|
+
|
|
14
|
+
The claim is read from lockmaster's state, `$(git rev-parse
|
|
15
|
+
--git-common-dir)/lockmaster/changes/<item>.json`. A write anywhere else (a
|
|
16
|
+
worktree that is no change's) is not this hook's business.
|
|
17
|
+
Standard library only; it does not need lockmaster installed.
|
|
18
|
+
"""
|
|
19
|
+
import fnmatch
|
|
20
|
+
import json
|
|
21
|
+
import os
|
|
22
|
+
import subprocess
|
|
23
|
+
import sys
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
|
|
26
|
+
LIVE = ("open", "queued", "landing", "waiting", "red")
|
|
27
|
+
LEDGER = "work/NOW.md"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def norm(path):
|
|
31
|
+
p = path.replace("\\", "/").strip()
|
|
32
|
+
while p.startswith("./"):
|
|
33
|
+
p = p[2:]
|
|
34
|
+
return p.rstrip("/") if p not in ("", "/") else p
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def claimed(path, claims):
|
|
38
|
+
"""The same rule as lockmaster's repo.claimed: a claim names the path, a
|
|
39
|
+
directory above it, or a glob matching it."""
|
|
40
|
+
path = norm(path)
|
|
41
|
+
for c in map(norm, claims):
|
|
42
|
+
if c in ("", ".", "*", "**") or path == c or path.startswith(c + "/"):
|
|
43
|
+
return True
|
|
44
|
+
if any(ch in c for ch in "*?[") and (fnmatch.fnmatchcase(path, c) or fnmatch.fnmatchcase(path, c + "/*")):
|
|
45
|
+
return True
|
|
46
|
+
return False
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def git(args, cwd):
|
|
50
|
+
r = subprocess.run(["git"] + args, cwd=cwd, capture_output=True, text=True)
|
|
51
|
+
return r.stdout.strip() if r.returncode == 0 else None
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _locate(file_path):
|
|
55
|
+
"""(live changes, the worktree's top, its path there, whether it is the primary checkout)."""
|
|
56
|
+
d = file_path.parent
|
|
57
|
+
while not d.is_dir() and d != d.parent:
|
|
58
|
+
d = d.parent
|
|
59
|
+
top = git(["rev-parse", "--show-toplevel"], str(d))
|
|
60
|
+
common = git(["rev-parse", "--git-common-dir"], str(d))
|
|
61
|
+
if not top or not common:
|
|
62
|
+
return [], None, None, False
|
|
63
|
+
common = Path(common) if os.path.isabs(common) else Path(d) / common
|
|
64
|
+
changes = common / "lockmaster" / "changes"
|
|
65
|
+
if not changes.is_dir():
|
|
66
|
+
return [], None, None, False
|
|
67
|
+
live = []
|
|
68
|
+
for f in sorted(changes.glob("*.json")):
|
|
69
|
+
try:
|
|
70
|
+
c = json.loads(f.read_text(encoding="utf-8"))
|
|
71
|
+
except (OSError, ValueError):
|
|
72
|
+
continue
|
|
73
|
+
if c.get("status") in LIVE:
|
|
74
|
+
live.append(c)
|
|
75
|
+
real_top = os.path.realpath(top)
|
|
76
|
+
rel = norm(os.path.join(os.path.relpath(os.path.realpath(str(file_path.parent)), real_top), file_path.name))
|
|
77
|
+
listing = git(["worktree", "list", "--porcelain"], str(d)) or ""
|
|
78
|
+
first = listing.splitlines()[0][len("worktree "):] if listing.startswith("worktree ") else ""
|
|
79
|
+
return live, real_top, rel, bool(first) and os.path.realpath(first) == real_top
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def change_for(file_path):
|
|
83
|
+
"""(change, path relative to its worktree) when `file_path` is inside a live change's worktree."""
|
|
84
|
+
live, top, rel, _ = _locate(file_path)
|
|
85
|
+
for c in live:
|
|
86
|
+
if os.path.realpath(c.get("worktree", "")) == top:
|
|
87
|
+
return c, rel
|
|
88
|
+
return None, None
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def claimants_in_checkout(file_path):
|
|
92
|
+
"""(path, [live changes claiming it]) when `file_path` is in the primary checkout."""
|
|
93
|
+
live, top, rel, primary = _locate(file_path)
|
|
94
|
+
if not primary or rel == LEDGER or rel.startswith(".claude/worktrees/"):
|
|
95
|
+
return rel, []
|
|
96
|
+
return rel, [c for c in live if os.path.realpath(c.get("worktree", "")) != top
|
|
97
|
+
and claimed(rel, c.get("paths", []))]
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def main():
|
|
101
|
+
try:
|
|
102
|
+
hook = json.loads(sys.stdin.read() or "{}")
|
|
103
|
+
except ValueError:
|
|
104
|
+
return 0
|
|
105
|
+
tool_input = hook.get("tool_input") or {}
|
|
106
|
+
raw = tool_input.get("file_path") or tool_input.get("notebook_path")
|
|
107
|
+
if not raw:
|
|
108
|
+
return 0
|
|
109
|
+
p = Path(raw)
|
|
110
|
+
if not p.is_absolute():
|
|
111
|
+
p = Path(hook.get("cwd") or os.getcwd()) / p
|
|
112
|
+
change, rel = change_for(p)
|
|
113
|
+
if change is None:
|
|
114
|
+
rel, others = claimants_in_checkout(p)
|
|
115
|
+
if not others:
|
|
116
|
+
return 0
|
|
117
|
+
msg = ("lockmaster: {} claims `{}`; edit it in its worktree ({}) or land this edit through lockmaster "
|
|
118
|
+
"(`lockmaster save`). Left uncommitted here, it makes {} wait to land.").format(
|
|
119
|
+
" and ".join(c["item"] for c in others), rel,
|
|
120
|
+
", ".join(c.get("worktree", "?") for c in others), "that change" if len(others) == 1 else "them")
|
|
121
|
+
elif claimed(rel, change.get("paths", [])):
|
|
122
|
+
return 0
|
|
123
|
+
else:
|
|
124
|
+
msg = ("lockmaster: `{}` is outside the claim of {} ({}). It will be left behind, not landed. "
|
|
125
|
+
"If it belongs to this change: `lockmaster claim add {}`.").format(
|
|
126
|
+
rel, change["item"], ", ".join(change.get("paths", [])) or "nothing claimed", rel)
|
|
127
|
+
print(json.dumps({"systemMessage": msg,
|
|
128
|
+
"hookSpecificOutput": {"hookEventName": "PreToolUse", "additionalContext": msg}}))
|
|
129
|
+
return 0
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
if __name__ == "__main__":
|
|
133
|
+
sys.exit(main())
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Disk budget — the repository's disk-budget law (L9 in codelaw, L14 in fux and
|
|
3
|
+
sheetpane; the record that owns this hook says which).
|
|
4
|
+
|
|
5
|
+
The budget lives in one place, work/MACHINE.md §Disk budget's `budget` row.
|
|
6
|
+
What counts is the whole project: the repo (its .git and every worktree under
|
|
7
|
+
it), every worktree outside it, and a CARGO_TARGET_DIR outside it.
|
|
8
|
+
|
|
9
|
+
pre PreToolUse — an action that would grow the project into an
|
|
10
|
+
unapproved GB raises a permission prompt
|
|
11
|
+
post PostToolUse — a yes approves exactly one GB; says so the moment
|
|
12
|
+
the project has grown past what was approved
|
|
13
|
+
prompt UserPromptSubmit — shows the usage from 80 % of the budget
|
|
14
|
+
fresh by hand — measures now and prints; exit 1 past the ceiling
|
|
15
|
+
|
|
16
|
+
Hook input is JSON on stdin. A measurement is reused for 60 seconds.
|
|
17
|
+
"""
|
|
18
|
+
import json
|
|
19
|
+
import math
|
|
20
|
+
import os
|
|
21
|
+
import re
|
|
22
|
+
import subprocess
|
|
23
|
+
import sys
|
|
24
|
+
import time
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
|
|
27
|
+
ROOT = Path(__file__).resolve().parents[2]
|
|
28
|
+
STATE = ROOT / ".claude" / ".disk-usage"
|
|
29
|
+
NUDGED = ROOT / ".claude" / ".disk-nudged"
|
|
30
|
+
MACHINE = ROOT / "work" / "MACHINE.md"
|
|
31
|
+
CACHE_S = 60
|
|
32
|
+
|
|
33
|
+
# Decision 3: a new sub-agent or worktree asks from 90 % of the ceiling.
|
|
34
|
+
NEW_TOOLS = {"Agent", "Task", "EnterWorktree"}
|
|
35
|
+
GROWS = re.compile(
|
|
36
|
+
r"\b(cargo|rustup|npm|npx|pnpm|yarn|bun|pip3?|uv|maturin|poetry|make|cmake"
|
|
37
|
+
r"|docker|tar|unzip|curl|wget|python3? -m (pip|build|venv)"
|
|
38
|
+
r"|git (worktree add|clone|fetch|pull|lfs))\b")
|
|
39
|
+
NEW_BASH = re.compile(r"\bgit worktree add\b")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def budget_gb():
|
|
43
|
+
try:
|
|
44
|
+
text = MACHINE.read_text(encoding="utf-8")
|
|
45
|
+
except OSError:
|
|
46
|
+
return 5.0
|
|
47
|
+
m = re.search(r"^\|\s*budget\s*\|\s*([\d.]+)\s*GB", text, re.M)
|
|
48
|
+
return float(m.group(1)) if m else 5.0
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def load():
|
|
52
|
+
try:
|
|
53
|
+
return json.loads(STATE.read_text(encoding="utf-8"))
|
|
54
|
+
except (OSError, ValueError):
|
|
55
|
+
return {"ts": 0, "kb": 0, "approved_gb": 0, "pending": {}}
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def save(st):
|
|
59
|
+
tmp = STATE.with_suffix(".tmp")
|
|
60
|
+
tmp.write_text(json.dumps(st), encoding="utf-8")
|
|
61
|
+
os.replace(tmp, STATE)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def du_kb(path):
|
|
65
|
+
r = subprocess.run(["du", "-sk", str(path)], capture_output=True, text=True)
|
|
66
|
+
try:
|
|
67
|
+
return int(r.stdout.split()[0])
|
|
68
|
+
except (IndexError, ValueError):
|
|
69
|
+
return 0
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def inside(p):
|
|
73
|
+
try:
|
|
74
|
+
Path(p).resolve().relative_to(ROOT)
|
|
75
|
+
return True
|
|
76
|
+
except ValueError:
|
|
77
|
+
return False
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def measure():
|
|
81
|
+
"""Decision 2: the repo, worktrees outside it, a target dir outside it."""
|
|
82
|
+
kb = du_kb(ROOT)
|
|
83
|
+
out = subprocess.run(["git", "worktree", "list", "--porcelain"], cwd=ROOT,
|
|
84
|
+
capture_output=True, text=True).stdout
|
|
85
|
+
for line in out.splitlines():
|
|
86
|
+
if line.startswith("worktree "):
|
|
87
|
+
p = line[9:]
|
|
88
|
+
if not inside(p) and Path(p).is_dir():
|
|
89
|
+
kb += du_kb(p)
|
|
90
|
+
target = os.environ.get("CARGO_TARGET_DIR")
|
|
91
|
+
if target and Path(target).is_dir() and not inside(target):
|
|
92
|
+
kb += du_kb(target)
|
|
93
|
+
return kb
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def usage(st, fresh=False):
|
|
97
|
+
if fresh or time.time() - st.get("ts", 0) > CACHE_S:
|
|
98
|
+
st["kb"], st["ts"] = measure(), time.time()
|
|
99
|
+
gb = st["kb"] / 1024 / 1024
|
|
100
|
+
budget = budget_gb()
|
|
101
|
+
if gb < budget:
|
|
102
|
+
# Back under the budget, the approvals are forgotten.
|
|
103
|
+
st["approved_gb"] = 0
|
|
104
|
+
NUDGED.unlink(missing_ok=True)
|
|
105
|
+
return gb, budget, max(budget, st.get("approved_gb", 0))
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def emit(event, **fields):
|
|
109
|
+
print(json.dumps({"hookSpecificOutput": {"hookEventName": event, **fields}}))
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def growing(tool, inp):
|
|
113
|
+
"""'new' (a sub-agent or worktree), 'grow' (a build or install) or None."""
|
|
114
|
+
if tool in NEW_TOOLS:
|
|
115
|
+
return "new"
|
|
116
|
+
if tool == "Bash":
|
|
117
|
+
cmd = inp.get("command", "")
|
|
118
|
+
if NEW_BASH.search(cmd):
|
|
119
|
+
return "new"
|
|
120
|
+
if GROWS.search(cmd):
|
|
121
|
+
return "grow"
|
|
122
|
+
return None
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def pre(hook, st):
|
|
126
|
+
kind = growing(hook.get("tool_name", ""), hook.get("tool_input") or {})
|
|
127
|
+
if not kind:
|
|
128
|
+
return
|
|
129
|
+
gb, budget, ceiling = usage(st)
|
|
130
|
+
threshold = ceiling * 0.9 if kind == "new" else ceiling
|
|
131
|
+
if gb < threshold:
|
|
132
|
+
return
|
|
133
|
+
need = math.floor(gb) + 1 if gb >= ceiling else int(ceiling) + 1
|
|
134
|
+
now = time.time()
|
|
135
|
+
st["pending"] = {k: v for k, v in st.get("pending", {}).items() if now - v["ts"] < 3600}
|
|
136
|
+
st["pending"][hook.get("tool_use_id", "")] = {"gb": need, "ts": now}
|
|
137
|
+
emit("PreToolUse", permissionDecision="ask", permissionDecisionReason=(
|
|
138
|
+
f"Disk budget: the project uses {gb:.1f} GB against a {budget:g} GB budget"
|
|
139
|
+
f" (approved ceiling {ceiling:g} GB). Allowing this "
|
|
140
|
+
f"{'new agent or worktree' if kind == 'new' else 'action'} approves one more GB,"
|
|
141
|
+
f" up to {need} GB (work/MACHINE.md §Disk budget). Deny it to clean up instead."))
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def post(hook, st):
|
|
145
|
+
tool, inp = hook.get("tool_name", ""), hook.get("tool_input") or {}
|
|
146
|
+
notes = []
|
|
147
|
+
p = st.get("pending", {}).pop(hook.get("tool_use_id", ""), None)
|
|
148
|
+
if p:
|
|
149
|
+
st["approved_gb"] = max(st.get("approved_gb", 0), p["gb"])
|
|
150
|
+
notes.append(f"Disk budget: the decider approved one more GB — the ceiling is now {p['gb']} GB.")
|
|
151
|
+
if growing(tool, inp):
|
|
152
|
+
gb, budget, ceiling = usage(st, fresh=True)
|
|
153
|
+
if gb >= ceiling:
|
|
154
|
+
mark = f"{ceiling:g}"
|
|
155
|
+
if not NUDGED.exists() or NUDGED.read_text(encoding="utf-8") != mark:
|
|
156
|
+
NUDGED.write_text(mark, encoding="utf-8")
|
|
157
|
+
notes.append(f"Disk budget: the project has grown to {gb:.1f} GB, past the approved"
|
|
158
|
+
f" {ceiling:g} GB (budget {budget:g} GB). Stop growing it: the next"
|
|
159
|
+
" build, install, agent or worktree asks the decider first.")
|
|
160
|
+
if notes:
|
|
161
|
+
emit("PostToolUse", additionalContext=" ".join(notes))
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def prompt(_hook, st):
|
|
165
|
+
gb, budget, ceiling = usage(st)
|
|
166
|
+
if gb >= budget * 0.8:
|
|
167
|
+
print(f"<disk>Disk budget: {gb:.1f} GB used of a {budget:g} GB budget"
|
|
168
|
+
f"{f' (approved to {ceiling:g} GB)' if ceiling > budget else ''}"
|
|
169
|
+
" — work/MACHINE.md §Disk budget.</disk>")
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def fresh(_hook, st):
|
|
173
|
+
gb, budget, ceiling = usage(st, fresh=True)
|
|
174
|
+
state = "under the budget" if gb < budget else (
|
|
175
|
+
"inside the approved GB" if gb < ceiling else "PAST the approved ceiling")
|
|
176
|
+
print(f"{gb:.2f} GB used · budget {budget:g} GB · approved ceiling {ceiling:g} GB · {state}")
|
|
177
|
+
return 0 if gb < ceiling else 1
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def main(argv):
|
|
181
|
+
mode = argv[0] if argv else "fresh"
|
|
182
|
+
hook = {}
|
|
183
|
+
if mode not in ("fresh", "prompt") and not sys.stdin.isatty():
|
|
184
|
+
try:
|
|
185
|
+
hook = json.loads(sys.stdin.read() or "{}")
|
|
186
|
+
except ValueError:
|
|
187
|
+
hook = {}
|
|
188
|
+
fn = {"pre": pre, "post": post, "prompt": prompt, "fresh": fresh}.get(mode)
|
|
189
|
+
if fn is None:
|
|
190
|
+
print(f"usage: disk-budget.py pre|post|prompt|fresh (got {mode})", file=sys.stderr)
|
|
191
|
+
return 2
|
|
192
|
+
st = load()
|
|
193
|
+
rc = fn(hook, st) or 0
|
|
194
|
+
save(st)
|
|
195
|
+
return rc
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
if __name__ == "__main__":
|
|
199
|
+
sys.exit(main(sys.argv[1:]))
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
# PostToolUse(Write|Edit|MultiEdit|NotebookEdit|Bash) — catches a malformed
|
|
3
|
+
# "Blocked on …" section the moment a session writes one. Bash is in the
|
|
4
|
+
# matcher because a session told to prefer the shell edits files that way.
|
|
5
|
+
# Also catches a 🟡 row that does not name its blocker right after its id.
|
|
6
|
+
# The rules are SR-WORK-OPEN-QUEUE rule 45a and its 🟡-blocker rule — stated once there, NOT here.
|
|
7
|
+
set -uo pipefail
|
|
8
|
+
cd "$(dirname "$0")/../.." || exit 0
|
|
9
|
+
git rev-parse --git-dir >/dev/null 2>&1 || exit 0
|
|
10
|
+
[ -f work/OPEN-WORK.md ] || exit 0
|
|
11
|
+
|
|
12
|
+
REASON=$(python3 scripts/check-open-work-inbox.py 2>/dev/null)
|
|
13
|
+
[ -z "$REASON" ] && exit 0
|
|
14
|
+
|
|
15
|
+
jq -n --arg r "$REASON" '{hookSpecificOutput:{hookEventName:"PostToolUse",decision:"block",
|
|
16
|
+
reason:($r + " — fix the section to match the record before continuing.")}}'
|
|
17
|
+
exit 0
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
# UserPromptSubmit — the ONLY hook whose stdout Claude sees as context.
|
|
3
|
+
# Prepends anything waiting on a human, so a blocker cannot go unmentioned.
|
|
4
|
+
set -uo pipefail
|
|
5
|
+
cd "$(dirname "$0")/../.." || exit 0
|
|
6
|
+
rm -f .claude/.stop-attempts .claude/.progress-nudged
|
|
7
|
+
|
|
8
|
+
if [ -s work/BLOCKED.json ] && ! jq -e '.decision == "PROCEED"' work/BLOCKED.json >/dev/null 2>&1; then
|
|
9
|
+
echo "<blocked>"; cat work/BLOCKED.json; echo "</blocked>"
|
|
10
|
+
echo "A blocker is open. Say so in your first sentence before anything else."
|
|
11
|
+
fi
|
|
12
|
+
|
|
13
|
+
# Noon of a YYYY-MM-DD as epoch seconds, by BSD or GNU date; empty if neither parses it.
|
|
14
|
+
epoch() { date -j -f "%Y-%m-%d %H:%M" "$1 12:00" +%s 2>/dev/null || date -d "$1 12:00" +%s 2>/dev/null; }
|
|
15
|
+
|
|
16
|
+
# The inbox stores no age (SR-WORK-OPEN-QUEUE rule 40): add the column here,
|
|
17
|
+
# today minus each row's `filed`, on every prompt.
|
|
18
|
+
with_age() {
|
|
19
|
+
local today line filed f
|
|
20
|
+
today=$(epoch "$(date +%Y-%m-%d)")
|
|
21
|
+
while IFS= read -r line; do
|
|
22
|
+
filed=$(printf '%s' "$line" | grep -oE '\| [0-9]{4}-[0-9]{2}-[0-9]{2} \|' | head -1 | tr -d '| ')
|
|
23
|
+
case "$line" in
|
|
24
|
+
"| what"*) echo "$line age |" ;;
|
|
25
|
+
"|---"*) echo "$line---|" ;;
|
|
26
|
+
"|"*) f=""; [ -n "$filed" ] && f=$(epoch "$filed")
|
|
27
|
+
if [ -n "$f" ] && [ -n "$today" ]; then echo "$line $(( (today - f + 43200) / 86400 )) d |"
|
|
28
|
+
else echo "$line |"; fi ;;
|
|
29
|
+
*) echo "$line" ;;
|
|
30
|
+
esac
|
|
31
|
+
done
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
if [ -f work/OPEN-WORK.md ]; then
|
|
35
|
+
DECIDER=$(git config user.name 2>/dev/null); DECIDER=${DECIDER:-the decider}
|
|
36
|
+
INBOX=$(sed -n '/^## Blocked on /,/^---$/p' work/OPEN-WORK.md | sed '1d;$d')
|
|
37
|
+
# A queue that stores its own age column (fux's) keeps it; any other gets one computed.
|
|
38
|
+
case "$INBOX" in *'| age |'*) ;; *) INBOX=$(printf '%s\n' "$INBOX" | with_age) ;; esac
|
|
39
|
+
case "$INBOX" in
|
|
40
|
+
*"*Empty since"*|"") ;;
|
|
41
|
+
*) echo "<inbox>"; echo "$INBOX"; echo "</inbox>"
|
|
42
|
+
echo "These are waiting on $DECIDER. Name them in your first three lines, with their age." ;;
|
|
43
|
+
esac
|
|
44
|
+
fi
|
|
45
|
+
|
|
46
|
+
if [ -s work/NOW.md ]; then
|
|
47
|
+
N=$(grep -v '^---' work/NOW.md | grep -v '^type:' | grep -v '^description:' | grep -v '^<!--' | grep -v '^-->' | grep -v '^ ' | grep -v '^$' | head -1)
|
|
48
|
+
case "$N" in
|
|
49
|
+
idle*|"") ;;
|
|
50
|
+
*) echo "<in-flight>$N</in-flight>"
|
|
51
|
+
echo "That is where the last session stopped. Confirm or correct it in your first line." ;;
|
|
52
|
+
esac
|
|
53
|
+
fi
|
|
54
|
+
exit 0
|