ckb/.agents/skills/ckb-lint/scripts/session_start.py
Michał Kopeć bbfda5a65d Sync: local changes as of 2026-10-29T13:50:12Z
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-29 14:50:12 +01:00

229 lines
9 KiB
Python

#!/usr/bin/env python3
"""Rule E in one call: everything the agent checks at session start, printed
as one short block so the prompt does not have to describe five commands.
session_start.py [--title "..."] [--root DIR] [--today YYYY-MM-DD] [--no-git]
What it prints, one line each (plus the tail of the latest workload note):
identity: Name <email> the git identity, or the OS user with a hint
title: <title> (set | kept | none) --title stores it unless one is already stored
announce: yes | no conversations.announce_title in ckb.yaml
git: <branch line>, N changed, M untracked -> "suggest ckb-sync-changes" when any
ckb check: clean | <counts> lint_report.py --quick -> "suggest ckb-lint"
autosave: ... autosave_hook.py --check, only when it needs action
routines: none due | DUE <name>: ... routines.py --due, one line per due routine
workload: <file> (last block follows) latest workload/ note by filename date
Exit 0 unless the repo root is not a KB. Python 3.8+, standard library only.
The scripts it wraps keep their own single-purpose interfaces; this one only
sequences them so a session start costs one tool call instead of five.
"""
import argparse
import getpass
import os
import re
import subprocess
import sys
from datetime import datetime
from pathlib import Path
HERE = Path(__file__).resolve().parent
SKILLS = HERE.parent.parent
LINT = HERE / "lint_report.py"
SAVE = SKILLS / "ckb-add-conversation" / "scripts" / "save_conversation.py"
AUTOSAVE = SKILLS / "ckb-add-conversation" / "scripts" / "autosave_hook.py"
ROUTINES = SKILLS / "ckb-routine" / "scripts" / "routines.py"
TITLES_DIR = Path("tmp") / "conversation-titles"
WORKLOAD_TAIL_LINES = 40
def run(cmd, cwd):
try:
p = subprocess.run(cmd, cwd=str(cwd), capture_output=True, text=True, timeout=120)
return p.returncode, (p.stdout or "").strip(), (p.stderr or "").strip()
except (OSError, subprocess.SubprocessError) as e:
return 127, "", str(e)
def py(script, args, cwd):
if not script.is_file():
return 127, "", f"{script} missing"
return run([sys.executable, "-I", str(script)] + args, cwd)
# ---------------------------------------------------------------- pieces
def identity(root):
name = run(["git", "config", "user.name"], root)[1]
email = run(["git", "config", "user.email"], root)[1]
if name or email:
return f"{name} <{email}>" if name and email else (name or email)
user = os.environ.get("USER") or os.environ.get("USERNAME") or getpass.getuser()
return f"{user} (OS user; git identity unset — set git config --global user.name / user.email)"
def yaml_flag(root, block, key, default):
"""Minimal reader for `block:\\n key: value` in ckb.yaml; no YAML parser."""
path = root / "ckb.yaml"
if not path.exists():
return default
in_block = False
for raw in path.read_text(encoding="utf-8").splitlines():
line = raw.split("#", 1)[0].rstrip()
if not line.strip():
continue
if not line.startswith((" ", "\t")):
in_block = line.strip() == f"{block}:"
continue
if in_block and line.strip().startswith(f"{key}:"):
return line.split(":", 1)[1].strip().lower() in ("true", "yes", "on")
return default
def stored_title(root):
"""The title already stored for the newest session of this project, if any."""
sys.path.insert(0, str(SAVE.parent))
try:
import save_conversation as sc # noqa: E402
except Exception:
return None
finally:
sys.path.pop(0)
try:
pdir = sc.project_dir_for(root)
sessions = sc.list_sessions(pdir) if pdir.is_dir() else []
if not sessions:
return None
return sc.stored_title(root, sessions[0]["id"])
except Exception:
return None
def title_line(root, wanted):
current = stored_title(root)
if wanted and wanted.strip():
if current:
return f"title: {current} (kept — already set this session)"
code, out, err = py(SAVE, ["--set-title", wanted.strip()], root)
if code == 0:
return f"title: {wanted.strip()} (set)"
return f"title: {wanted.strip()} (NOT stored: {err or out or code})"
return f"title: {current} (kept)" if current else "title: none (pass --title on a new session)"
def git_line(root):
code, out, _ = run(["git", "status", "--short", "--branch"], root)
if code != 0:
return "git: not a git repository", False
lines = out.splitlines()
branch = lines[0].lstrip("# ").strip() if lines else "?"
rest = lines[1:]
untracked = sum(1 for l in rest if l.startswith("??"))
changed = len(rest) - untracked
unsynced = "ahead" in branch or "behind" in branch or changed or untracked
parts = [branch]
if changed:
parts.append(f"{changed} changed")
if untracked:
parts.append(f"{untracked} untracked")
line = "git: " + ", ".join(parts)
if unsynced:
line += " -> suggest ckb-sync-changes"
return line, bool(unsynced)
def lint_line(root, today):
args = ["--quick"] + (["--today", today] if today else [])
code, out, err = py(LINT, args, root)
if code == 127:
return f"ckb check: unavailable ({err})"
# A crash prints a traceback to stderr; its last line names the error and keeps the block short.
tail = (out or err).strip().splitlines()
line = tail[-1] if tail else "ckb check: (no output)"
if not out.strip() and err.strip():
line = f"ckb check: failed ({line})"
return line + (" -> suggest ckb-lint" if code != 0 else "")
def autosave_line(root):
auto = yaml_flag(root, "conversations", "autosave", False)
hook = (root / ".claude" / "settings.local.json").exists()
if not auto and not hook:
return None # Rule E: skip entirely
code, out, err = py(AUTOSAVE, ["--check"], root)
if code == 0:
return None # consistent: stay quiet
return f"autosave: {out or err} -> ask once before changing .claude/settings.local.json"
def routines_lines(root, today):
if not ROUTINES.is_file() or not (root / "ckb.yaml").exists():
return ["routines: none due"]
args = ["--due"] + (["--today", today] if today else [])
code, out, err = py(ROUTINES, args, root)
if code == 0:
return ["routines: none due"]
if code == 1 and out:
lines = out.splitlines()
return ["routines: DUE " + lines[0]] + [" DUE " + l for l in lines[1:]] + \
[" -> finish the user's request, then run each (ckb-routine)"]
return [f"routines: check failed ({err or out or code})"]
def latest_workload(root):
"""Newest workload note by the date prefix of its filename, any author;
ties broken by modification time. Returns (path, last block) or (None, '')."""
wdir = root / "workload"
if not wdir.is_dir():
return None, ""
files = [f for f in wdir.glob("*.md") if re.match(r"\d{4}-\d{2}-\d{2}", f.name)]
if not files:
return None, ""
files.sort(key=lambda f: (f.name[:10], f.stat().st_mtime))
latest = files[-1]
text = latest.read_text(encoding="utf-8", errors="replace")
blocks = re.split(r"(?m)^(?=## )", text)
block = blocks[-1].rstrip() if len(blocks) > 1 else text.rstrip()
lines = block.splitlines()
if len(lines) > WORKLOAD_TAIL_LINES:
lines = lines[:WORKLOAD_TAIL_LINES] + ["…"]
return latest, "\n".join(lines)
# ---------------------------------------------------------------- main
def main(argv=None):
ap = argparse.ArgumentParser(description="Rule E session-start checks in one call.")
ap.add_argument("--title", help="store this title for the session unless one is already stored")
ap.add_argument("--root", default=".", help="KB root (default: current directory)")
ap.add_argument("--today", help="override today's date, YYYY-MM-DD (tests)")
ap.add_argument("--no-git", action="store_true", help="skip the git status line (tests)")
a = ap.parse_args(argv)
root = Path(a.root).resolve()
if a.today and not re.fullmatch(r"\d{4}-\d{2}-\d{2}", a.today):
sys.exit("error: --today must be YYYY-MM-DD")
if not (root / "wiki").is_dir():
sys.exit(f"error: {root} has no wiki/ — not a Cascade KB root")
out = [f"identity: {identity(root)}", title_line(root, a.title),
f"announce: {'yes' if yaml_flag(root, 'conversations', 'announce_title', True) else 'no'}"]
if not a.no_git:
out.append(git_line(root)[0])
out.append(lint_line(root, a.today))
auto = autosave_line(root)
if auto:
out.append(auto)
out.extend(routines_lines(root, a.today))
path, block = latest_workload(root)
if path:
out.append(f"workload: {path.relative_to(root).as_posix()} — last block:")
out.append(block)
else:
out.append("workload: none yet")
print("\n".join(out))
return 0
if __name__ == "__main__":
sys.exit(main())