Faults: add automatic disk-free, disk-drop, and checkouts tripwires
ci / test (push) Canceled after 0s

This commit is contained in:
swaits committed 2026-11-25 10:34:51 -07:00
1 parent 4ab516c803
commit cf27d4a767
7 files changed
+226 -45

No files matched your search

+1 -1
View File
@@ -44,7 +44,7 @@ Hooks (the agent tool calls these): sisi tick | prompt | watch | gate
Your own rules, models table and retro log live in ~/.local/share/sisi ($SISI_DATA, else $XDG_DATA_HOME/sisi), a git repository;
a project's rules live in its .sisi/rules.md. Settings: "core" in
its config.json (gate, meter, direct_calls, direct_extension, rules_lines, rules_chars, organize_after,
research_days, shell_workers, worker_minutes, retro_minutes)."""
research_days, shell_workers, worker_minutes, retro_minutes, disk_free_percent, disk_drop_percent, checkouts)."""
def main(argv):
+64 -25
View File
@@ -6,7 +6,7 @@ USAGE = 'usage: sisi fault "<what is wrong, 4+ words>" | --started N "<fix>" | -
HEAD = 'sisi: open faults. Fix each now or say what blocks it (`sisi fault --started N "<fix>"` | `--blocked N "<blocker>"` | `--fixed N "<evidence>"`):'
BLOCK = 'sisi: open fault(s) with no fix started and no blocker named: %s. Start a fix (`sisi fault --started N "<fix>"`), name what blocks it (`sisi fault --blocked N "<blocker and unblock>"`), or close it (`sisi fault --fixed N "<evidence>"`).'
_path = lambda cwd=None: os.path.join(store.STATE, "core-faults", store.project_key(cwd) + ".json")
_gb = lambda b: "%d GB" % round(b / 1e9) if b >= 1e9 else "%.1f GB" % (b / 1e9)
def _load(p, strict=False):
d = os.path.dirname(p)
@@ -24,20 +24,76 @@ def _load(p, strict=False):
raise OSError("%s is not valid JSON" % p)
return {"next": 1, "items": []}
def _fmt(f):
s = max(0, int(time.time() - f["at"])) if type(f.get("at")) in (int, float) and f["at"] == f["at"] and abs(f["at"]) < 1e12 else 0
age = "%ds" % s if s < 60 else "%dm" % (s // 60) if s < 3600 else "%dh" % (s // 3600) if s < 86400 else "%dd" % (s // 86400)
return "#%d [%s, %s] %s%s" % (f["id"], f["state"], age, f["text"], " — " + str(f["note"]) if f.get("note") else "")
def lines(cwd=None):
return [_fmt(f) for f in _load(_path(cwd))["items"]]
def show(cwd=None, gate=False):
opened = [f for f in _load(_path(cwd))["items"] if not gate or f["state"] == "open"]
return (BLOCK % "; ".join("#%d %s" % (f["id"], f["text"]) for f in opened) if gate else "\n".join([HEAD] + [_fmt(f) for f in opened])) if opened else ""
def gate(cwd=None):
opened = [f for f in _load(_path(cwd))["items"] if f["state"] == "open"]
return BLOCK % "; ".join("#%d %s" % (f["id"], f["text"]) for f in opened) if opened else ""
def add(cwd, text, kind="", flag="", fid=0):
p = _path(cwd)
with store.lock(p):
doc = _load(p, strict=True)
if os.path.exists(p) and not (os.stat(p).st_mode & 0o200):
raise OSError("%s is read-only" % p)
if flag:
hit = next((f for f in doc["items"] if f["id"] == fid), None)
if not hit:
return None
doc["items"] = [f for f in doc["items"] if f["id"] != fid] if flag == "--fixed" else doc["items"]
hit.update(state=flag[2:], note=text)
else:
if kind and any(f.get("kind") == kind for f in doc["items"]):
return None
hit = {"id": doc["next"], "state": "open", "at": time.time(), "text": text, "note": "", **({"kind": kind} if kind else {})}
doc["next"], doc["items"] = doc["next"] + 1, doc["items"] + [hit]
out = json.dumps(doc)
if len(out.encode("utf-8")) > 64000:
raise OSError("%s would exceed 64,000 bytes" % p)
store.write(p, out)
return hit
def _checkouts(cwd):
try:
cur = os.path.abspath(cwd)
while not os.path.lexists(g := os.path.join(cur, ".git")) and cur != os.path.dirname(cur):
cur = os.path.dirname(cur)
first = lambda p: ((store.regular(p, True)[1] or b"").decode("utf-8", "replace").splitlines() or [""])[0].strip()
common = g if os.path.isdir(g) and not os.path.islink(g) else ""
if not common and (line := first(g)).startswith("gitdir:"):
gd = os.path.normpath(os.path.join(cur, line[7:].strip()))
cd = first(os.path.join(gd, "commondir"))
common = os.path.normpath(os.path.join(gd, cd)) if cd else (os.path.dirname(os.path.dirname(gd)) if os.path.basename(os.path.dirname(gd)) == "worktrees" else gd)
return len(os.listdir(wt)) if common and os.path.isdir(wt := os.path.join(common, "worktrees")) else 0
except OSError:
return 0
def check(cwd, start_free=None):
cfg, hits, pos = store.config(), [], lambda k: type(cfg[k]) in (int, float) and cfg[k] > 0
try:
st = os.statvfs(cwd) if pos("disk_free_percent") or (pos("disk_drop_percent") and type(start_free) in (int, float)) else None
total, free = (st.f_blocks * st.f_frsize, st.f_bavail * st.f_frsize) if st else (0, 0)
if total > 0 and pos("disk_free_percent") and free * 100 < cfg["disk_free_percent"] * total:
hits.append(("disk_free", "The disk holding this project is %d%% full (%s free). Find what this work made (copies, checkouts, build folders) and remove it." % (round(100 * (total - free) / total), _gb(free))))
if total > 0 and pos("disk_drop_percent") and type(start_free) in (int, float) and (start_free - free) * 100 > cfg["disk_drop_percent"] * total:
hits.append(("disk_drop", "This session's work has used %s of disk. Remove what is finished before making more." % _gb(start_free - free)))
except OSError:
pass
if pos("checkouts") and (n := _checkouts(cwd)) > cfg["checkouts"]:
hits.append(("checkouts", "This repository has %d checkouts. Remove the ones whose work is merged or abandoned." % n))
have, unsaved = {f.get("kind") for f in _load(_path(cwd))["items"]}, []
for kind, text in [h for h in hits if h[0] not in have]:
try:
add(cwd, text, kind)
except OSError:
unsaved.append("[open] " + text)
return "\n".join([HEAD] + ls) if (ls := lines(cwd) + unsaved) else ""
def run(args, cwd=None):
if not args:
@@ -46,25 +102,8 @@ def run(args, cwd=None):
body = " ".join(" ".join(args[2:] if flag else args).split())[:300]
if (flag and (len(args) < 3 or not args[1].isdecimal() or len(body.split()) < 2)) or (not flag and (args[0].startswith("-") or len(body.split()) < 4)):
return print(USAGE) or 1
p = _path(cwd)
try:
with store.lock(p):
doc = _load(p, strict=True)
if os.path.exists(p) and not (os.stat(p).st_mode & 0o200):
raise OSError("%s is read-only" % p)
if flag:
hit = next((f for f in doc["items"] if f["id"] == int(args[1])), None)
if not hit:
return print("sisi fault: #%s not found; %s" % (args[1], USAGE)) or 1
doc["items"] = [f for f in doc["items"] if f["id"] != hit["id"]] if flag == "--fixed" else doc["items"]
hit.update(state=flag[2:], note=body)
else:
hit = {"id": doc["next"], "state": "open", "at": time.time(), "text": body, "note": ""}
doc["next"], doc["items"] = doc["next"] + 1, doc["items"] + [hit]
out = json.dumps(doc)
if len(out.encode("utf-8")) > 64000:
raise OSError("%s would exceed 64,000 bytes" % p)
store.write(p, out)
hit = add(cwd, body, flag=flag, fid=int(args[1]) if flag else 0)
except OSError as e:
return print("sisi fault: %s" % e) or 1
return print(_fmt(hit)) or 0
return print(_fmt(hit)) or 0 if hit else print("sisi fault: #%s not found; %s" % (args[1], USAGE)) or 1
+13 -9
View File
@@ -97,28 +97,32 @@ def say(text):
def _begin(state, cwd):
if "started" not in state:
state.update(started=time.time(), project=store.project_key(cwd), snapshot=store.snapshot(cwd))
try:
state["free_bytes"] = (st := os.statvfs(cwd)).f_bavail * st.f_frsize
except OSError:
pass
def _faults(cwd, gate=False):
if not os.path.lexists(os.path.join(store.STATE, "core-faults", store.project_key(cwd) + ".json")):
def _faults(cwd, gate=False, free=None):
if gate and not os.path.lexists(os.path.join(store.STATE, "core-faults", store.project_key(cwd) + ".json")):
return ""
from . import faults
return faults.show(cwd, gate)
return faults.gate(cwd) if gate else faults.check(cwd, free)
def tick(p):
"""Session start: remember where the work began; print this project's learned rules and what is due."""
sid, cwd, worker = p["session_id"], p["cwd"] or os.getcwd(), p["subagent"]
sid, cwd, worker, free = p["session_id"], p["cwd"] or os.getcwd(), p["subagent"], None
if sid:
with store.session(sid) as s:
_begin(s, cwd)
worker = worker or bool(s.get("worker"))
worker, free = worker or bool(s.get("worker")), s.get("free_bytes")
env = os.environ.get("CLAUDE_ENV_FILE")
if env and re.fullmatch(r"[A-Za-z0-9_-]+", str(sid)):
store.append(env, "export SISI_SESSION_ID=%s" % sid) # so `sisi retro` knows its session
if not os.path.exists(os.path.join(store.DATA, "generated", "core.md")):
rules.build_rulebook()
text = "\n".join(x for x in (rules.project_text(cwd), rules.due(cwd), models.stale(), "" if worker else _faults(cwd)) if x)
text = "\n".join(x for x in (rules.project_text(cwd), rules.due(cwd), models.stale(), "" if worker else _faults(cwd, False, free)) if x)
if text:
print(text)
return 0
@@ -126,18 +130,18 @@ def tick(p):
def prompt(p):
"""Each request: a new turn begins. The first request tells a delegated worker from a lead."""
sid, cwd, worker = p["session_id"], p["cwd"] or os.getcwd(), p["subagent"]
sid, cwd, worker, free = p["session_id"], p["cwd"] or os.getcwd(), p["subagent"], None
if sid:
with store.session(sid) as s:
_begin(s, cwd)
if not s.get("prompts") and WORKER.search(p["prompt"][:2000]):
s["worker"] = True
worker = worker or bool(s.get("worker"))
worker, free = worker or bool(s.get("worker")), s.get("free_bytes")
s["prompts"] = s.get("prompts", 0) + 1
s.get("prompts_since") or s.update(began=time.time()) # the first request of a piece of work
s["prompts_since"] = s.get("prompts_since", 0) + 1
s["direct"], s["extra"], s["blocks"] = 0, 0, 0
not worker and (text := _faults(cwd)) and print(text)
not worker and (text := _faults(cwd, False, free)) and print(text)
return 0
+1 -1
View File
@@ -21,7 +21,7 @@ LIB = os.environ.get("SISI_LIB") or os.path.join(HOME, ".local", "lib", "sisi")
# Every setting there is. The person overrides one under "core" in config.json in their store.
DEFAULTS = {"gate": True, "meter": True, "direct_calls": 8, "direct_extension": 8,
"rules_lines": 30, "rules_chars": 4000, "organize_after": 8, "research_days": 7, "shell_workers": False,
"worker_minutes": 15, "retro_minutes": 5}
"worker_minutes": 15, "retro_minutes": 5, "disk_free_percent": 20, "disk_drop_percent": 5, "checkouts": 8}
def config():